MarcoMorawec / SiB-Dev-Team

All SiB Dev Team Mojo
4 stars 0 forks source link

Lab 2 Shortcuts #13

Open MarcoMorawec opened 11 years ago

MarcoMorawec commented 11 years ago

Creating the project (part 1 )

Create a new Rails project (including postgres database): rails new my_app --database=postgresql

Create the pg database: rake db:create:all

Create the controller: rails generate controller restaurant --> fill in the CRUD actions for index, show, update, delete

Create the migration rails generate migration restaurant --> Run the migration rake db:migrate

Create the model rails generate model restaurant --> add the attr_accessible :description, :address, etc. to the model

create the first database entries in the rails console rails console Restaurant.create(:description => "Hungry Mother", :address => "Main Street")

create an index.html.erb in app/views

            <%= restaurant.name %>
            <%= restaurant.description %>
<% end %> 

Adjust the routes.rb so it points to the correct root -->delete index.html from app/puplic --> in routes.rb add

Create the views for show and edit(Delete action can be handled with :confirm):

Add CRUD links to views: <%= link_to("Show", {:action => 'show', :id => restaurant.id}) %> <%= link_to("Edit", {:action => 'edit', :id => restaurant.id}) %> <%= link_to("Delete Restaurant", {:action => 'destroy', :id => restaurant.id}, :confirm => "Are you sure you want to delete?") %>```


__Link pages together__:
```<%= link_to("<<Back to Restaurant Listing", {:action => 'index'}) %>

TESTING:

Creating the testing database:

Helpful commands if you're in trouble:


rake db:test:clone  Recreate the test database from the current environment's database schema
rake db:test:clone_structure    Recreate the test database from the development structure
rake db:test:load   Recreate the test database from the current schema.rb
rake db:test:prepare    Check for pending migrations and load the test schema
rake db:test:purge  Empty the test database.

Creating Functional tests OR controller tests:

-> for index (in functional/restaurants_controller_test.rb)

    get :index
    assert_response :success
    assert_not_nil assigns(:restaurant)
  end
  test "create exists" do
    assert_difference('Restaurant.count') do
        post :create, restaurant: {:name => 'a', :description => 'b', :street => 'c', 
            :streetnumber => '5', :city => 'd', :zipcode => '9', :state => 'MA', :country => 'USA', 
            :phonenumber => '123'}
    end
    assert_redirected_to :action => 'index'
  end

running a test:

or

--> Output: '.'(dot) means the test passes, F means failed, E means error

--> this was hard and I had to comment a few tests out after hours of trying to get my controller actions to pass

Twitter Bootstrapping it (Part 2)

Source with video: is here Bootstrap Gem Repo is here

--> gemfile add:

--> Now get the styling into your rails project

rails g bootstrap:install

--> I want my site to be responsive so I'm going with:

rails g bootstrap:layout app_name fluid

--> Warning, this will create all your views for you, so if you like to style you're views yourself, this will mess you up

Add Images (Part 3)

--> get your homebrew installation updated and upgraded here

--> Install imagemagick (help)

--> Use the Carrierwave gem here; Install help is here

--> Add the carrierwave gem to the gemfile:


gem 'carrierwave'

--> bundle install

--> create image uploader class

--> now we need to create a migration so images can be uploaded to the database:

rails g migration add_image_to_restaurants image:string

```rake db:migrate

__Let's set-up the views and model:

--> Make sure you to add :image to attr_accessible in your restaurant.rb model.

Also add the following to your restaurant.rb model file:

To your form_for (or edit.html.erb file) add multipart:


<%= form_for(:restaurant, :url => {:action => 'create'}, :html => { :class => 'form-horizontal', :multipart => true}) do |f| %>

Now give the form a field to upload the :image (if you're using twitter bootstrap it might look like this):


  <div class="control-group">
    <%= f.label :image, :class => 'control-label' %>
    <div class="controls">
      <%= f.file_field :image, :class => 'image_area' %>
    </div>
  </div>

Bonus: Image upload via URL

--> add to restaurants.rb model:

attr_accessible: :remote_image_url

Show the image in your index view by adding:

<%= image_tag(restaurant.image_url.to_s) %>

Create thumbnails (different sized images) on upload using RMagick

--> Documentation for how to do that is here. Look for RMagick, resize_to_limit(width, height) here

In image_uploader.rb:

-> include:

and add the image resize actions:


version :thumb do
      process :resize_to_limit => [300, 250]
   end

   version :masthead do
      process :resize_to_limit => [600, 500]
   end

--> to make this work we need the RMagick gem in the gemfile:

--> Adjust the views so the correct version shows up (thumb for index and masthead for show action):


<%= image_tag(restaurant.image_url(:thumb).to_s %>
<%= image_tag(restaurant.image_url(:masthead).to_s) %>

Adding AWS S3:

Install the fog gem to handle the upload of files to the cloud, here


gem 'fog'
bundle install

--> Next sign up for AWS and create a bucket for this project

--> Next get your environment variables into a safe place (access keys and secret access keys) Use the figaro gem here

bundle install
rails generate figaro:install

--> add the following to the created locales/application.yml file:

 AWS_ACCESS_KEY_ID: you key
  AWS_SECRET_ACCESS_KEY:  your secret key
  AWS_BUCKET: your aws bucket

Now, edit your carrierMagick gem to make stuff work:

--> In your initializer folder create a file called "carrierwave.rb" to point your app to the right location, add this:

CarrierWave.configure do |config|
  config.fog_credentials = {
    :provider               => 'AWS',                        
    :aws_access_key_id      => ENV['AWS_ACCESS_KEY_ID'],                        
    :aws_secret_access_key  => ENV['AWS_SECRET_ACCESS_KEY'],                     
  }
  config.fog_directory  = ENV['AWS_BUCKET']                     
end

--> in uploaders/image_uploader.rb set the storage to:

storage :fog

and also include:

include CarrierWave::MimeTypes
  process :set_content_type

--> S3 should work now

Adding Static Google maps

Now this is tricky! You need to pass in the longitude and latitude into the static google maps image for this to work.

Here's how to implement the static google maps:

<img src="http://maps.googleapis.com/maps/api/staticmap?center=-1477788990,8873788992&markers=-1477788990,8873788992&zoom=10&size=300x200&sensor=false"></img>

--> Since we only have address in our database we need to convert the address into longitude and latitude Use the gem geocoder, here

gem 'geocoder'
bundle install

--> now we need to create a field in the database to store the longitude and latitude as floats:

rails generate migration AddLatitudeAndLongitudeToModel latitude:float longitude:float
rake db:migrate

--> create a location.rb model and make the variables accessible add:

  attr_accessible :longitude, :latitude

--> In the restaurant.rb model add:

geocoded_by :address

--> If you don't have an address field you can try setting up an action, but that didn't work for me.

--> In the view add the longitude and latitude conversion into the static google map:

<img src="http://maps.googleapis.com/maps/api/staticmap?center=<%= restaurant.geocode[0].to_s %>,<%= restaurant.geocode[1].to_s %>&markers=<%= restaurant.geocode[0].to_s %>,<%= restaurant.geocode[1].to_s %>&zoom=10&size=300x200&sensor=false"></img>
MarcoMorawec commented 11 years ago

Damn it -> I'm finally done with this one. On to the next one!