diff --git a/_posts/2014-05-29-touristic-autism_basic-app.markdown b/_posts/2014-05-29-touristic-autism_basic-app.markdown new file mode 100644 index 00000000..a819f88b --- /dev/null +++ b/_posts/2014-05-29-touristic-autism_basic-app.markdown @@ -0,0 +1,161 @@ +--- +layout: default +title: Touristic Autism-friendly Spots App +permalink: touristic-autism_basic-app +--- + +# Basic Web Application + +*Created by Myriam Leggieri, [@iammyr](https://twitter.com/iammyr)* +*for [Rails Girls Galway](https://github.com/RailsGirlsGalway)* +The basic guides that have been merged and adapted are the [Ruby on Rails Tutorial](http://www.railstutorial.org/book), the [basic RailsGirls app](http://guides.railsgirls.com/app/) and the tutorials for [creating thumbnails](http://guides.railsgirls.com/thumbnails), [authenticating users](http://guides.railsgirls.com/devise/), [adding design](http://guides.railsgirls.com/design), [deploying to OpenShift](http://guides.railsgirls.com/openshift/) and [adding comments](http://guides.railsgirls.com/commenting). + + + +## Get to know the tools + +
+ +

 

+ +

Text Editor

+ +

Sublime Text, Komodo Edit, Vim, Emacs, and Gedit are examples of text editors your can use for writing code and editing files.

+ +

 

+ +

Terminal (known as Command Prompt on Windows)

+Where you start the rails server and run commands. + +

 

+ +

Web browser

+(Firefox, Safari, Chrome) for viewing your application. + +

GitHub

+[Slides - by Kevin Lyda @]() + +
+ +### Important + +It is important that you select the instructions specific to your operating system - the commands you need to run on a Windows computer are slightly different to Mac or Linux. If you're having trouble check the Operating System switcher at the bottom of the commands. + + +## *1.*Creating the application + +We're going to create a new Rails app called *railsgirls-galway-2014*. + +First, let's open a terminal: + +* Mac OS X: Open Spotlight, type *Terminal* and click the *Terminal* application. +* Windows: Click Start and look for *Command Prompt*, then click *Command Prompt with Ruby on Rails*. +* Linux (Ubuntu/Fedora): Search for *Terminal* on the dash and click *Terminal*. + +Next, type these commands in the terminal: + +
+
+{% highlight sh %} +mkdir projects +{% endhighlight %} + +
+

You can verify that a directory named projects was created by running the list command: ls. You should see the projects directory in the output. Now you want to change the directory you are currently in to the projects folder by running:

+
+ +{% highlight sh %} +cd projects +{% endhighlight %} + +
+

You can verify you are now in an empty directory or folder by again running the ls command. Now you want to create a new app called railsgirls by running:

+
+ +{% highlight sh %} +rails new railsgirls-galway-2014 +{% endhighlight %} + +
+

This will create a new app in the folder railsgirls, so we again want to change the directory to be inside of our rails app by running:

+
+ +{% highlight sh %} +rvm rubygems latest +cd railsgirls-galway-2014 +{% endhighlight %} + +
+

If you run ls inside of the directory you should see folders such as app and config. You can then start the rails server by running:

+
+ +{% highlight sh %} +rails server +{% endhighlight %} +
+ +
+{% highlight sh %} +mkdir projects +{% endhighlight %} + +
+

You can verify that a directory named projects was created by running the list command: dir. You should see the projects directory in the output. Now you want to change the directory you are currently in to the projects folder by running:

+
+ +{% highlight sh %} +cd projects +{% endhighlight %} + +
+

You can verify you are now in an empty directory or folder by again running the dir command. Now you want to create a new app called railsgirls by running:

+
+ +{% highlight sh %} +rails new railsgirls-galway-2014 +{% endhighlight %} + +
+

This will create a new app in the folder railsgirls, so we again want to change the directory to be inside of our rails app by running:

+
+ +{% highlight sh %} + +cd railsgirls +{% endhighlight %} + +
+

If you run dir inside of the directory you should see folders such as app and config. You can then start the rails server by running:

+
+ +{% highlight sh %} +rails server +{% endhighlight %} +
+
+ +Open [http://localhost:3000](http://localhost:3000) in your browser. You should see "Welcome aboard" page, which means that the generation of your new app worked correctly. + +Notice in this window the command prompt is not visible because you are now in the Rails server, the command prompt looks like this: + +
+
+{% highlight sh %} +$ +{% endhighlight %} +
+
+{% highlight sh %} +> +{% endhighlight %} +
+
+ +When the command prompt is not visible you cannot execute new commands. If you try running `cd` or another command it will not work. To return to the normal command prompt: + +Hit `CTRL-C` in the terminal to quit the server. + +**Coach:** Explain what each command does. +[What is a web application and a server - Slides by @]() +The skeleteon generated by "rails new" reflects the [Model-View-Controller - Slides by @]() architectural pattern. + diff --git a/_posts/2014-05-29-touristic-autism_continuous-deployment.markdown b/_posts/2014-05-29-touristic-autism_continuous-deployment.markdown new file mode 100644 index 00000000..fa44d380 --- /dev/null +++ b/_posts/2014-05-29-touristic-autism_continuous-deployment.markdown @@ -0,0 +1,159 @@ +--- +layout: default +title: Touristic Autism-friendly Spots App +permalink: touristic-autism_continuous-deployment +--- + +# Continuous Deployment + +*Created by Myriam Leggieri, [@iammyr](https://twitter.com/iammyr)* +*for [Rails Girls Galway](https://github.com/RailsGirlsGalway)* +The basic guides that have been merged and adapted are the [Ruby on Rails Tutorial](http://www.railstutorial.org/book), the [basic RailsGirls app](http://guides.railsgirls.com/app/) and the tutorials for [creating thumbnails](http://guides.railsgirls.com/thumbnails), [authenticating users](http://guides.railsgirls.com/devise/), [adding design](http://guides.railsgirls.com/design), [deploying to OpenShift](http://guides.railsgirls.com/openshift/) and [adding comments](http://guides.railsgirls.com/commenting). + + + +We’re going to deploy our (still-empty) Rails application to production. Deploying early and often allows us to catch any deployment problems early in our development cycle or else there could be troubles during the integration phases. +Several shared hosts, virtual private servers, full-service deployment companies and cloud deployment services all provide facilities that makes it very easy to deploy Rails applications. + +OpenShift is one of the cloud deployment services offering such facilities. It is a cloud computing Platform as a Service (PaaS) that makes it easy to deploy apps online. It is open source and written in Ruby. + + + +[Create an OpenShift Online account](https://openshift.redhat.com/app/account/new?web_user[promo_code]=railsgirls), which allows you to put three apps online for free. Once you are signed up, install the OpenShift RHC Client Tools by adding the rhc gem in the production environment. Add the following to the Gemfiile (which is written in Ruby ndr): + +
+
+ {% highlight sh %} + group :production do + gem install rhc + end +{% endhighlight %} +
+If you are not using RVM or RailsInstaller then follow [this guide](https://www.openshift.com/developers/rhc-client-tools-install) (you may need to do "sudo gem install rhc"). +
+ +Then run in the terminal: + +
+
+ {% highlight sh %} + bundle install --without production + rhc setup +{% endhighlight %} +
+The --without production option prevents the local installation of any production gems. + +If Bundler complains about a readline error, try adding gem ’rb-readline’ to your Gemfile. + +Because the only gems we’ve added are restricted to a production environment, right now this command doesn’t actually install any additional local gems, but it’s needed to update Gemfile.lock. Now, let's commit these changes to GitHub! +
+ +**Coach:** Explain the benefits of deploying to a PaaS such as OpenShift, as opposed to traditional servers. What "production" means. Discuss SSH and why we need to upload a public key to communicate securely. +[Slides by Gerry Kavanagh @gerryk]() + +Navigate to the "projects" folder. Run in the prompt: + +
+
+ {% highlight sh %} +rhc app create openshiftapp ruby-1.9 postgresql-9.2 --from-code=https://github.com/openshift/rails-example.git +{% endhighlight %} +
+
+ +We need the .openshift directory and config/database.yml file from the sample application in order for our Rails app to run on OpenShift. Copy these from the openshiftapp directory to the railsgirls directory. + +
+
+ {% highlight sh %} +cd railsgirls-galway-2014 +cp -r ../openshiftapp/.openshift . +cp ../openshiftapp/config/database.yml config +{% endhighlight %} +
+Now add and commit in Git the new changes! +
+ +OpenShift uses the PostgreSQL database, which means that we need to add the pg gem in the production environment to allow Rails to talk to Postgres. Note also the addition of the rails_12factor gem, which is used to serve static assets such as images and stylesheets. Substitute "gem sqlite" in Gemfile with the following: + +
+
+ {% highlight sh %} +gem 'sqlite3', :group => [:development, :test] +gem 'pg', :group => [:production] +gem 'rails_12factor', :group => [:production] +{% endhighlight %} +
+Now do a bundle excluding the gems in production. + +On some platforms, this may generate platform-specific versions of your Gems that cause issues when you push your app to the cloud. To prevent this, open your Gemfile.lock file and check the versions of the ‘sqlite3’ and ‘pg’ Gems. If they have a platform-specific suffix, such as -x86-mingw32, remove this (eg. change pg (0.16.0-x86-mingw32) to pg (0.16.0) and sqlite3 (1.3.8-x86-mingw32) to sqlite3 (1.3.8)). Save and close the file, and run the above bundle command again before continuing. + +Add and commit your changes in Git +
+ +**Coach:** Talk about relational databases and the differences between SQLite and PostgreSQL. + + +We are now ready to deploy the Rails Girls app to OpenShift. We need to tell our Git repository where to push the code. To get the location of your OpenShift code repository, run the following command, and copy the Git URL from the output. + +
+
+ {% highlight sh %} + rhc app show openshiftapp +{% endhighlight %} +
+
+ +Now run the following commands, replacing the SSH string with your Git URL. We are using ‘-f’ for force here because we are happy to wipe away the history of the current OpenShift repository, which contains the sample Rails app. When you are pushing future changes, you can just use ‘git push’. + +
+
+ {% highlight sh %} +git remote add openshift ssh://5387bff65973cadf3c000323@openshiftapp-railsgirlsgalway.rhcloud.com/~/git/openshiftapp.git/ +git push -f --set-upstream openshift master +{% endhighlight %} +
+Refresh the app in your browser to see the result. +If the app fails to visualize (500 Internal Server Error) often (error from the rhc tail openshiftapp : "Missing `secret_key_base` for 'production' environment, set this value in `config/secrets.yml`") the following solves. +Get a secret with "rake secret" assign it to the environment variable 'SECRET_KEY_BASE' and export the variable to ~/.bash_profile. +OpenShift (but also Heroku) needs to serve static assets like images and CSS: + +
+
+ {% highlight sh %} +$ rake assets:precompile +$ git add . +$ git commit -am "Add precompiled assets for OpenShift" +git push -f --set-upstream openshift master +{% endhighlight %} +
+To be used only if OpenShift fails without it. We'll cover "rake" and "assets" later on. +
+
+ +When we push a new version of the application, anything stored within OpenShift’s copy of the repo will be wiped to make way for the new files. This includes some log files and the images uploaded by users. To fix this, we can store these files in persistent directories on OpenShift instead; the filepaths of the locations we need are stored in environment variables. + +To change the location of the production log, open config/environments/production.rb. Beneath the comment line: + +
+
+ {% highlight sh %} +config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) +{% endhighlight %} +
+
+ +Add the line: + +
+
+ {% highlight sh %} +config.logger = ActiveSupport::Logger.new(File.join(ENV['OPENSHIFT_RUBY_LOG_DIR'], "production.log")) +{% endhighlight %} +
+Rails 3 users: Change ‘ActiveSupport::Logger’ to ‘ActiveSupport::BufferedLogger’. +
+ +You can tail your application’s logs with the command rhc tail openshiftapp (the output from the change you just made won’t show up until the new file has been committed and pushed to OpenShift). + +**Coach:** Discuss the value of application logging. diff --git a/_posts/2014-05-29-touristic-autism_design.markdown b/_posts/2014-05-29-touristic-autism_design.markdown new file mode 100644 index 00000000..a4fad514 --- /dev/null +++ b/_posts/2014-05-29-touristic-autism_design.markdown @@ -0,0 +1,347 @@ +--- +layout: default +title: Touristic Autism-friendly Spots App +permalink: touristic-autism_design +--- + +# Design + +*Created by Myriam Leggieri, [@iammyr](https://twitter.com/iammyr)* +*for [Rails Girls Galway](https://github.com/RailsGirlsGalway)* +The basic guides that have been merged and adapted are the [Ruby on Rails Tutorial](http://www.railstutorial.org/book), the [basic RailsGirls app](http://guides.railsgirls.com/app/) and the tutorials for [creating thumbnails](http://guides.railsgirls.com/thumbnails), [authenticating users](http://guides.railsgirls.com/devise/), [adding design](http://guides.railsgirls.com/design), [deploying to OpenShift](http://guides.railsgirls.com/openshift/) and [adding comments](http://guides.railsgirls.com/commenting). + +**Coach:** Talk about the relationship between HTML and Rails. What part of views is HTML and what is Embedded Ruby (ERB)? What is MVC and how does this relate to it? (Models and controllers are responsible for generating the HTML views.) + +The app doesn't look very nice yet. Let's do something about that. We'll use the Twitter Bootstrap project to give us nicer styling really easily. + +Open `app/views/layouts/application.html.erb` in your text editor and above the line + +{% highlight erb %} +<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %> +{% endhighlight %} + +add + +{% highlight erb %} + + +{% endhighlight %} + +and replace + +{% highlight erb %} +<%= yield %> +{% endhighlight %} + +with + +{% highlight erb %} +
+ <%= yield %> +
+{% endhighlight %} + +Let's also add a navigation bar and footer to the layout. In the same file, above `
` add + +{% highlight html %} + +{% endhighlight %} + +and before `` add + +{% highlight html %} + + +{% endhighlight %} + +Now let's also change the styling of the places table. Open `app/assets/stylesheets/application.css` and at the bottom add + +{% highlight css %} +body { padding-top: 100px; } +footer { margin-top: 100px; } +table, td, th { vertical-align: middle; border: none; } +th { border-bottom: 1px solid #DDD; } +{% endhighlight %} + +Now make sure you saved your files and refresh the browser to see what was changed. You can also change the HTML & CSS further. + +In case your Terminal shows you an error message that *sort of* implies there is something wrong with your JavaScript or CoffeeScript, install [nodejs](http://nodejs.org/download/). This issue should not appear when you've used the RailsInstaller (but when you've installed Rails via ```gem install rails```). + +**Coach:** Talk a little about CSS and layouts. + + +1.Design your header + ++ put the following code to the bottom of `app/assets/stylesheets/application.css`: + + ``` + .navbar { + min-height: 38px; + background-color: #f55e55; + } + ``` + + Now refresh the page and check the changes. You can try change the + color or font of the header. You can check the color reference + from [http://color.uisdc.com/](http://color.uisdc.com/). + + **Coach: ** talk about the property `display`, inline and block element. + ++ Then put these lines at the bottom: + + ``` + .navbar a.brand { font-size: 18px; } + .navbar a.brand:hover { + color: #fff; + background-color: transparent; + text-decoration: none; + } + ``` + + **Coach: ** explain the 4 states of a link + + +2.Design your table + + + We simply use the twitter [Bootstrap](http://www.bootcss.com/) to + polish our table。find this line from + app/views/places/index.html.erb and replace: + + ``` + + ``` + + with + + ``` +
+ ``` + + + Modify size of the picture using the following lines + + ``` + <%= image_tag(idea.picture_url, :width => 600) if idea.picture.present? %> + ``` + + try to change the width and see what's gonna happen + + + + add the following lines to the bottom of file app/assets/stylesheets/places.css.scss: + + ``` + .container a:hover { + color: #f55e55; + text-decoration: none; + background-color: rgba(255, 255, 255, 0); + } + ``` + + + + try add some background style with property `background-image`, + reference to + [http://subtlepatterns.com/](http://subtlepatterns.com/) for some patterns. + + +3.add style to footer + ++ add the lines to bottom of app/assets/stylesheets/application.css: + + ``` + footer { + background-color: #ebebeb; + padding: 30px 0; + } + ``` + + try put more things into `footer`, then adjust it's position. + +4.add style to button + + + open + [http://localhost:3000/places/new](http://localhost:3000/places/new) + and find the `Create Place` button. + + add these lines to app/assets/stylesheets/places.css.scss + + ``` + .container input[type="submit"] { + height: 30px; + font-size: 13px; + background-color: #f55e55; + border: none; + color: #fff; + } + ``` + + **Coach** explain how to use `border` in css, try modify the style + of button like round the corner, add shadow or color etc. + + + +Open `app/views/layouts/application.html.erb` in your text editor and replace the line + +{% highlight html %} + +{% endhighlight %} + +with + +{% highlight html %} + +{% endhighlight %} + +Open `app/assets/stylesheets/application.css`, replace the line + +{% highlight html %} +body { padding-top: 100px; } +{% endhighlight %} + +with + +{% highlight html %} +body { padding-top: 60px; } +{% endhighlight %} + +Finally, delete the file `app/assets/stylesheets/scaffolds.css.scss` because we don't really need the default style generated by Rails. + +Now refresh the page at [http://localhost:3000/places](http://localhost:3000/places). You will not find much change but it's good preparation for the following steps. + + +Considering "place" is the most important object in your app, we are going to put the "New Place" button on the navigation bar to make it always available. + +Open `app/views/layouts/application.html.erb`, under the line + +{% highlight erb %} +
  • Places
  • +{% endhighlight %} + +add +{% highlight erb %} +
  • <%= link_to 'New Place', new_place_path %>
  • +{% endhighlight %} + + + +Now it's time to make the place list page look professional. For that, we are going to replace the table layout with a div layout. + +**Coach:** Talk a little about table vs div. + +Open `app/views/places/index.html.erb` in your text editor and replace the table with + +{% highlight erb %} +<% @places.in_groups_of(3) do |group| %> +
    + <% group.compact.each do |place| %> +
    + + + <%= image_tag(place.picture_url, :width => '20%') if place.picture.present? %> +

    <%= link_to place.name, place %>

    + <%= place.description %> + + + <%= place.address %> + <%= place.latitude %> +<%= place.longitude %> + +<%= place.user_id %> +<%= link_to 'Show', place %> | + + <% if user_signed_in? %> + <% if current_user.id == place.user_id %>. + +<%= link_to 'Edit', edit_place_path(place) %> | +<%= link_to 'Destroy', place, method: :delete, data: { confirm: 'Are you sure?' } %> + + + <% end %> + <% end %> + +
    + <% end %> +
    +<% end %> +{% endhighlight %} + +**Coach:** Explain what the new code means line by line, and talk a little about Bootstrap 12 grids layout. + +Refresh it! We get a nice looking idea list. Click the "New Idea" button, and create more ideas with real text and pretty pictures - the page will look much better with content. There is a principle of contemporary web design: content is the best decoration. + +Click the title of a place, and you will be brought to the details page of the place. Now it is still scaffold generated by Rails, so let's make it better. + +Open `app/views/places/show.html.erb` in your text editor and replace all lines with + +{% highlight erb %} +

    Places created

    + +
    +
    + <%= image_tag(@place.picture_url, :width => "100%") if @place.picture.present? %> +
    + +
    +

    Name: <%= @place.name %>

    + +

    User Rating as Autism-friendly: <%= rating_for @place, "autism_friendly" %>

    +

    User Overall Rating: <%= rating_for @place, "overall" %>

    +

    Your Vote as Autism-friendly: <%= rating_for_user @place, current_user, "autism_friendly", :star => 7 %>

    +

    Your Overall Vote: <%= rating_for_user @place, current_user, "autism_friendly", :star => 7 %>

    + +

    Description: <%= @place.description %>

    +

    Address: <%= @place.address %>

    +

    Latitude: <%= @place.latitude %>

    +

    Longitude: <%= @place.longitude %>

    +

    Creator ID: <%= @place.user_id %>

    + +

    + <%= link_to 'Edit', edit_place_path(@place) %> | +<%= link_to 'Back', places_path %> +

    +
    +
    + +

    Comments

    +<% @comments.each do |comment| %> +
    + <%= comment.user_id %> +
    +

    <%= comment.body %>

    + + <% if user_signed_in? %> + <% if current_user.id == comment.user_id %> + +

    <%= link_to 'Delete', comment_path(comment), method: :delete, data: { confirm: 'Are you sure?' } %>

    + + <% end %> + <% end %> + +
    +<% end %> +<%= render 'comments/form' %> + +{% endhighlight %} + +Continue experimenting with Design changes! ;) + + diff --git a/_posts/2014-05-29-touristic-autism_git.markdown b/_posts/2014-05-29-touristic-autism_git.markdown new file mode 100644 index 00000000..3c6a8914 --- /dev/null +++ b/_posts/2014-05-29-touristic-autism_git.markdown @@ -0,0 +1,90 @@ +--- +layout: default +title: Touristic Autism-friendly Spots App +permalink: touristic-autism_git +--- + +# Version Control with Git + +*Created by Myriam Leggieri, [@iammyr](https://twitter.com/iammyr)* +*for [Rails Girls Galway](https://github.com/RailsGirlsGalway)* +The basic guides that have been merged and adapted are the [Ruby on Rails Tutorial](http://www.railstutorial.org/book), the [basic RailsGirls app](http://guides.railsgirls.com/app/) and the tutorials for [creating thumbnails](http://guides.railsgirls.com/thumbnails), [authenticating users](http://guides.railsgirls.com/devise/), [adding design](http://guides.railsgirls.com/design), [deploying to OpenShift](http://guides.railsgirls.com/openshift/) and [adding comments](http://guides.railsgirls.com/commenting). + + +Navigate to the root directory of the first app and initialize a new repository: + +
    +
    + {% highlight sh %} + $ git init + {% endhighlight %} +
    +
    + +Before adding the project to the repository, let's tell Git which files to ignore - because too frequently subject to changes - by listing them in the .gitignore file. The "rails new" command already create a .gitignore file but let's extend it with the following. + +
    +
    + {% highlight sh %} +# Ignore other unneeded files. +database.yml +# Ignore Rails documentation files +doc/ +# Ignore Vim and Emacs swap files +*.swp +*~ +.project +# Ignore (for OS X users) the .DS_Store directories created by the Mac Finder application +.DS_Store +.idea +.secret + {% endhighlight %} +
    +
    + +Add the changes (recursively adding every sub-directory, too). +
    +
    + {% highlight sh %} +git add . + {% endhighlight %} +
    +
    + +The "git add" command adds the project files to a staging area, which contains pending changes to your projectbu; you can see which files are in the staging area using the status command: + +
    +
    + {% highlight sh %} +$ git status + {% endhighlight %} +
    +
    + +Now commit the changes while justifying them with a message: +
    +
    + {% highlight sh %} +$ git commit -m "Initialize repository" + {% endhighlight %} +
    +Git commits are local, recorded only on the machine on which the commits occur. You can view a list of all the commit messages with "git log" typing "q" to quit. +
    + +Now we want our changes to be pushed from our local machine to a remote repository. +[Create a repository](http://github.com/new) called "railsgirls-galway-2014" and fill in the information. Do not to initialize the repository with a README file since "rails new" already created that automatically. +Push up your local changes to the remote repository as follows: + +
    +
    + {% highlight sh %} +$ git remote add origin https://github.com//railsgirls-galway-2014.git +$ git push -u origin master + {% endhighlight %} +
    +The result is a page at GitHub (for instance, [here's mine](https://github.com/iammyr/railsgirls-galway-2014)) for our application repository, which provides nice rendering, sharing functionalities and statistics: take a look by yourself at https://github.com//railsgirls-galway-2014 +
    + +**Coach:** Explain the branch-edit-commit-merge workflow on GitHub: modify the README file to be more descriptive. +([Slides by Myriam Leggieri @iammyr]()) + diff --git a/_posts/2014-05-29-touristic-autism_google-map.markdown b/_posts/2014-05-29-touristic-autism_google-map.markdown new file mode 100644 index 00000000..04152610 --- /dev/null +++ b/_posts/2014-05-29-touristic-autism_google-map.markdown @@ -0,0 +1,105 @@ +--- +layout: default +title: Touristic Autism-friendly Spots App +permalink: touristic-autism_google-map +--- + +# Show All Places in a Google Map + +*Created by Myriam Leggieri, [@iammyr](https://twitter.com/iammyr)* +*for [Rails Girls Galway](https://github.com/RailsGirlsGalway)* +The basic guides that have been merged and adapted are the [Ruby on Rails Tutorial](http://www.railstutorial.org/book), the [basic RailsGirls app](http://guides.railsgirls.com/app/) and the tutorials for [creating thumbnails](http://guides.railsgirls.com/thumbnails), [authenticating users](http://guides.railsgirls.com/devise/), [adding design](http://guides.railsgirls.com/design), [deploying to OpenShift](http://guides.railsgirls.com/openshift/) and [adding comments](http://guides.railsgirls.com/commenting). + + +We need to install a piece of software to let us display and interact with Google Maps. + +Open `Gemfile` in the project directory using your text editor and add + +{% highlight ruby %} +gem 'gmaps4rails' +{% endhighlight %} + + +Bundle as usual. Then add to a new app/model/marker.rb file: + +{% highlight sh %} +class Marker + + include ActiveModel::Validations + include Gmaps4rails::ActsAsGmappable + + acts_as_gmappable :position => :location + + attr_accessor :location + + def gmaps4rails_infowindow + 'foo' + end + +end +{% endhighlight %} + + + +Then add to config/application.rb within your project block: + +{% highlight sh %} +config.active_support.escape_html_entities_in_json = true +config.encoding = "utf-8" +config.filter_parameters += [:password] +config.assets.enabled = true +config.assets.version = '1.0' +{% endhighlight %} + +Create your app/controllers/google_controller.rb: + +{% highlight sh %} +class GoogleController < ApplicationController + def index; end + + def markers + @marker ||= (1..10).map { + m = Marker.new + m.location = [ (Random.new.rand(-5000..5000) / 100.0),(Random.new.rand(-5000..5000) / 100.0) ] + m + }.to_gmaps4rails + end + helper_method :markers + +end +{% endhighlight %} + +Create your view/google/index.html.erb: + +{% highlight sh %} +

    See some marker on your map by default

    +
    +<%= gmaps("markers" => {"data" => markers}, + 'last_map' => false, + "map_options" => { + "center_on_user" => true, + "detect_location" => true, + "provider" => "google", :id => 'google_map'}) %> + +

    See on OpenLayer

    +
    + +<%= gmaps("markers" => {"data" => markers}, + "map_options" => { + "center_on_user" => true, + "detect_location" => true, + "provider" => "openlayers", :id => 'openlayer_map'}) %> +{% endhighlight %} + +Add the following in app/views/application.html.erb after "<%= yield %>": + +{% highlight sh %} +<%= yield :scripts %> +{% endhighlight %} + +Finally add the following to your config/routes.rb: + +{% highlight sh %} + get '/google' => 'google#index' + root :to => 'google#index' +{% endhighlight %} diff --git a/_posts/2014-05-29-touristic-autism_image-upload.markdown b/_posts/2014-05-29-touristic-autism_image-upload.markdown new file mode 100644 index 00000000..cfcb98d5 --- /dev/null +++ b/_posts/2014-05-29-touristic-autism_image-upload.markdown @@ -0,0 +1,161 @@ +--- +layout: default +title: Touristic Autism-friendly Spots App +permalink: touristic-autism_image-upload +--- + +# Image Upload and Thumbnails + +*Created by Myriam Leggieri, [@iammyr](https://twitter.com/iammyr)* +*for [Rails Girls Galway](https://github.com/RailsGirlsGalway)* +The basic guides that have been merged and adapted are the [Ruby on Rails Tutorial](http://www.railstutorial.org/book), the [basic RailsGirls app](http://guides.railsgirls.com/app/) and the tutorials for [creating thumbnails](http://guides.railsgirls.com/thumbnails), [authenticating users](http://guides.railsgirls.com/devise/), [adding design](http://guides.railsgirls.com/design), [deploying to OpenShift](http://guides.railsgirls.com/openshift/) and [adding comments](http://guides.railsgirls.com/commenting). + + +We need to install a piece of software to let us upload files in Rails. + +Open `Gemfile` in the project directory using your text editor and add + +{% highlight ruby %} +gem 'carrierwave' +{% endhighlight %} + + +In the terminal run: + +{% highlight sh %} +bundle +{% endhighlight %} + +Now we can generate the code for handling uploads. In the terminal run: + +{% highlight sh %} +rails generate uploader Picture +{% endhighlight %} + +At this point you need to **restart the Rails server process** in the terminal. + +Hit `CTRL-C` in the terminal to quit the server. Once it has stopped, you can press the up arrow to get to the last command entered, then hit enter to start the server again. + +This is needed for the app to load the added library. + +Open `app/models/place.rb` and add + +{% highlight ruby %} +mount_uploader :picture, PictureUploader +{% endhighlight %} + +Open `app/views/places/_form.html.erb` and change + +{% highlight erb %} +<%= f.text_field :picture %> +{% endhighlight %} + +to + +{% highlight erb %} +<%= f.file_field :picture %> +{% endhighlight %} + +Sometimes, you might get an *TypeError: can't cast ActionDispatch::Http::UploadedFile to string*. + +If this happens, in file `app/views/places/_form.html.erb` change the line + +{% highlight erb %} +<%= form_for(@place) do |f| %> +{% endhighlight %} + +to + +{% highlight erb %} +<%= form_for @place, :html => {:multipart => true} do |f| %> +{% endhighlight %} + +Now if you run your server, and try adding a new place with a picture, you'll notice that the picture doesn't look nice because it only shows a path to the file. Let's fix that. + +Open `app/views/places/show.html.erb` and change + +{% highlight erb %} +<%= @place.picture %> +{% endhighlight %} + +to + +{% highlight erb %} +<%= image_tag(@place.picture_url, :width => 600) if @place.picture.present? %> +{% endhighlight %} + +Now refresh your browser to see what changed. + +**Coach:** Talk a little about HTML. + +__Coach__: Explain what specifying the image width in HTML at the end of Step +4 does and how it differs from resizing images on the server. + +## Installing ImageMagick + +* OS X: run `brew install imagemagick`. If you don't have the brew command, you can [install Homebrew here][in-homebrew]. +* Windows: download and run the [ImageMagick installer][im-win] (use the first + *download* link). +* Linux: On Ubuntu and Debian, run `sudo apt-get install imagemagick`. Use the + appropriate package manager instead of `apt-get` for other distributions. + + [im-win]: http://www.imagemagick.org/script/binary-releases.php?ImageMagick=vkv0r0at8sjl5qo91788rtuvs3#windows + [in-homebrew]: http://mxcl.github.io/homebrew/ + +__Coach__: What is ImageMagick and how is it different from libraries/gems we +used before? + +Open `Gemfile` in the project and add + +{% highlight ruby %} +gem 'mini_magick', '3.5.0' +{% endhighlight %} + +In the Terminal run: + +{% highlight sh %} +bundle +{% endhighlight %} + +## Telling our app to create thumbnails when an image is uploaded + +Open `app/uploaders/picture_uploader.rb` and find the line that looks like +this: + +{% highlight ruby %} + # include CarrierWave::MiniMagick +{% endhighlight %} + +Remove the `#` sign. + +__Coach__: Explain the concept of comments in code. + +Below the line you just changed, add: + +{% highlight ruby %} +version :thumb do + process :resize_to_fill => [50, 50] +end +{% endhighlight %} + +The images uploaded from now on should be resized, but the ones we already +have weren't affected. So edit one of the existing places and re-add a picture. + +## Displaying the thumbnails + +To see if the uploaded picture was resized open +`app/views/places/index.html.erb`. Change the line + +{% highlight erb %} + +{% endhighlight %} + +to + +{% highlight erb %} + +{% endhighlight %} + +Take a look at the list of ideas in the browser to see if the thumbnail is +there. + diff --git a/_posts/2014-05-29-touristic-autism_intro.markdown b/_posts/2014-05-29-touristic-autism_intro.markdown new file mode 100644 index 00000000..5f781f1b --- /dev/null +++ b/_posts/2014-05-29-touristic-autism_intro.markdown @@ -0,0 +1,115 @@ +--- +layout: default +title: Touristic Autism-friendly Spots App +permalink: touristic-autism_intro +--- + +# Rails Girls Touristic Autism-friendly Spots App Tutorial + +*Created by Myriam Leggieri, [@iammyr](https://twitter.com/iammyr)* +*for [Rails Girls Galway](https://github.com/RailsGirlsGalway)* + + +This guide merges, adapts and extends some of the basic RailsGirls guides **for the scenario**: description, displaying and commenting touristic places and rate them with respect to their autism-friendliness. This application was requested by the [Galway Autism Partnership](http://www.galwayautismpartnership.com/) to support autistic adults during their travelings. + +The extension comprises of the following **new features**: + +* TDD using Guide +* Resource Rating +* Authenticated User (via devise) permission setting + +The basic guides that have been merged and adapted are the [Ruby on Rails Tutorial](http://www.railstutorial.org/book), the [basic RailsGirls app](http://guides.railsgirls.com/app/) and the tutorials for [creating thumbnails](http://guides.railsgirls.com/thumbnails), [authenticating users](http://guides.railsgirls.com/devise/), [adding design](http://guides.railsgirls.com/design), [deploying to OpenShift](http://guides.railsgirls.com/openshift/) and [adding comments](http://guides.railsgirls.com/commenting). + + + +### [*0.*Installation](/install) + +**Make sure you have Rails and Git installed.** [**Follow the installation guide**](/install), the [**Installing Git section of Pro Git**](http://www.git-scm.com/book/en/Getting-Started-Installing-Git) to get set up. Then configure GitHub by typing the following in your terminal: +
    +
    +{% highlight sh %} +$ git config --global user.name "Your Name" +$ git config --global user.email your.email@example.com +{% endhighlight %} + +
    +

    one-time setup steps for GitHub.

    +
    +Sign up for a [free GitHub account](https://github.com/signup/free) if you don’t have one already. + + +### [*1.*Basic Web Application](/touristic-autism_basic-app) + +### [*2.*Version control with Git](/touristic-autism_git) + +### [*3.*Resource Modeling](/touristic-autism_resource-modeling) + +### [*4.*Resource Rating](/touristic-autism_resource-rating) + +### [*5.*Design](/touristic-autism_design) + +### [*6.*Image upload and Thumbnails](/touristic-autism_image-upload.markdown) + +**Optional - for advanced Rails Girls:** + +### [*7.*Continuous Deployment](/_posts/2014-05-29-touristic-autism_continuous-deployment.markdown) + +### [*8.*Continuous Testing and Integration](/_posts/2014-05-29-touristic-autism_static-pages-tdd.markdown) + + + + +## Additional Guides + +* Guide 0: [Handy cheatsheet for Ruby, Rails, console etc.](https://github.com/PragTob/rails-beginner-cheatsheet) +* Guide 1: [Put your app online with Heroku by Terence Lee](/heroku) / [Put your app online with OpenShift by Katie Miller](/openshift) / [Put your app online with Ninefold](/ninefold) / [Put your app online with Shelly Cloud](/shellycloud) / [Put your app online with anynines](/anynines) / [Put your app online with Trucker.io](/trucker) +* Guide 2: [Adding profile pictures with Gravatar](/gravatar) +* Guide 3: [Go through additional explanations for the App by Lucy Bain](https://github.com/lbain/railsgirls) + + +# Appendices + +## Undoing things + +Rails has some facilities to help you recover from mistakes. + +For instance, you may decide to change the name of a controller. Since, when generating a controller, Rails creates many more files than the controller file itself, undoing the generation means removing a whole set of files. In Rails, this can be accomplished with rails destroy. In particular, these two commands cancel each other out: + + $ rails generate controller FooBars baz quux + $ rails destroy controller FooBars baz quux + +Similarly, after we generate a model as follows: + + $ rails generate model Foo bar:string baz:integer + +This can be undone using + + $ rails destroy model Foo + + +Migrations change the state of the database using + + $ rake db:migrate + +We can undo a single migration step using + + $ rake db:rollback + +To go all the way back to the beginning, we can use + + $ rake db:migrate VERSION=0 + +As you might guess, substituting any other number for 0 migrates to that version number, where the version numbers come from listing the migrations sequentially. + +To drop a table from the db enter + + $ rails console + +Then just type: + + >> ActiveRecord::Migration.drop_table(:) + +You can browse directly the database (if sqlite3 type ".quit" to exit afterwards) by typing + + $ rails db + diff --git a/_posts/2014-05-29-touristic-autism_resource-modeling.markdown b/_posts/2014-05-29-touristic-autism_resource-modeling.markdown new file mode 100644 index 00000000..cbadbc3d --- /dev/null +++ b/_posts/2014-05-29-touristic-autism_resource-modeling.markdown @@ -0,0 +1,433 @@ +--- +layout: default +title: Touristic Autism-friendly Spots App +permalink: touristic-autism_resource-modeling +--- + +# Resource Modeling + +*Created by Myriam Leggieri, [@iammyr](https://twitter.com/iammyr)* +*for [Rails Girls Galway](https://github.com/RailsGirlsGalway)* +The basic guides that have been merged and adapted are the [Ruby on Rails Tutorial](http://www.railstutorial.org/book), the [basic RailsGirls app](http://guides.railsgirls.com/app/) and the tutorials for [creating thumbnails](http://guides.railsgirls.com/thumbnails), [authenticating users](http://guides.railsgirls.com/devise/), [adding design](http://guides.railsgirls.com/design), [deploying to OpenShift](http://guides.railsgirls.com/openshift/) and [adding comments](http://guides.railsgirls.com/commenting). + +What do we want our app to do? As a first thing, we would like to +* authenticate **users** +* allow authenticated users to create a new touristic **place** description +* allow authenticated users to **comment** those places +* allow authenticated users to **rate** up to which extent those places are autism-friendly or not. + +Note that these requirements help us identify 4 different resources: user, place, comment, rating. We are now going to model them specifying their properties and their associations with each other. + +We will enable the rating in the next tutorial. + + +## Authenticated Tourists/Users + +Let's generate our first resource: user and require its authentication. + +## Step 0: Add devise gem + +Open up your `Gemfile` and add this line + +{% highlight ruby %} +gem 'devise' +{% endhighlight %} +and run +{% highlight sh %} +bundle install +{% endhighlight %} +to install the gem. **Also remember to restart the Rails server**. + +## Step 1: Set up devise in your app + +Run the following command in the terminal. + +{% highlight sh %} +rails g devise:install +{% endhighlight %} + + +## Step 2: Configure Devise + +Ensure you have defined default url options in your environments files. Open up `config/environments/development.rb` and add this line: +{% highlight ruby %} + config.action_mailer.default_url_options = { :host => 'localhost:3000' } +{% endhighlight %} + +before the `end` keyword. + +Open up `app/views/layouts/application.html.erb` and add: + +{% highlight erb %} +<% if notice %> +

    <%= notice %>

    +<% end %> +<% if alert %> +

    <%= alert %>

    +<% end %> +{% endhighlight %} +right above +{% highlight ruby %} + <%= yield %> +{% endhighlight %} + + + +## Step 3: Setup the User model + +We'll use a bundled generator script to create the User model. +{% highlight sh %} + rails g devise user + rake db:migrate +{% endhighlight %} + +**Coach:** Explain what user model has been generated. What are the fields? Note that a model inherits abilities to interact with the DB from its ActiveRecord::Base super-class (ref. MVC). + +## Step 4: Create your first user + +Now that you have set everything up you can create your first user. Devise creates all the code and routes required to create accounts, log in, log out, etc. + +Make sure your rails server is running, open [http://localhost:3000/users/sign_up](http://localhost:3000/users/sign_up) and create your user account. + +## Step 5: Add sign-up and login links + +All we need to do now is to add appropriate links or notice about the user being logged in in the top right corner of the navigation bar. + +In order to do that, edit `app/views/layouts/application.html.erb` by adding at the beginning of the body: +{% highlight erb %} + +{% endhighlight %} + + +Finally, force the user to redirect to the login page if the user was not logged in. Open up `app/controllers/application_controller.rb` and add: + +{% highlight ruby %} + before_action :authenticate_user! +{% endhighlight %} + +after `protect_from_forgery with: :exception`. + +Open your browser and try logging in and out from. + +**Coach:** Talk about the `user_signed_in?` and `current_user` helpers. Why are they useful? + +Let's add-commit-push to your GitHub repo! See how nicely all the changes are now on your GitHub profile? :) + +## Touristic Places + +We now use Rails' scaffold functionality to generate and set up all that is necessary to list, add, remove, edit, and view our second resource: "touristic places". + +
    +
    +{% highlight sh %} +rails generate scaffold place name:string address:string latitude:decimal longitude:decimal description:text picture:string user_id:integer +{% endhighlight %} +
    +Note the column user:references that is created to support the 1-to-many association with Users. +
    + +The scaffold creates new files in your project directory. However, we have defined (modeled) a "structure" for our "place" resource and we want all the future instances of this resource to stick to this structure and get stored somewhere, i.e., in a database. +We are already using a database (see `gem 'sqlite'` in your Gemfile). Let's add the structure of "place" as a table to our database with the following. + +
    +
    +{% highlight sh %} +bin/rake db:migrate +{% endhighlight %} +
    + +
    +{% highlight sh %} +ruby bin/rake db:migrate +{% endhighlight %} +
    + + +Then start the server again. Open [http://localhost:3000/places](http://localhost:3000/places) in your browser and check out all the new functionalities that our web application is now providing to handle "place" resources. All thanks to what Ruby on Rails automatically generates with `generate scaffold`. +Each new instance of "place" that will be stored in the database, will be automatically assigned a unique identifier called "primary key", with no need for us to specify it as one of the fields (along with picture, name, etc.) +
    + + +**Coach:** What is Rails scaffolding? What are migrations and why do you need them? +Note the pages that have been created to manipulate the "place" resources and their naming convention. +Look at the server logging and explain it as a report of the following interaction (in the context of the MVC pattern): +* The browser issues a request for the /places URL. +* Rails routes /places to the index action in the Places controller. +* The index action asks the Place model to retrieve all places (Place.all). +* The Place model pulls all the places from the database. +* The Place model returns the list of places to the controller. +* The controller captures the users in the @users variable, which is passed to the index view. +* The view uses embedded Ruby to render the page as HTML. +* The controller passes the HTML back to the browser + +Note that the controller created is RESTful (explain) + +Note that the controller inherits abilities (large amount of functionality, such as the ability to manipulate model objects, filter inbound HTTP requests, and render views as HTML) from its ApplicationController super-class (ref. MVC). + +Open up `app/views/places/show.html.erb` and remove the line that says: + +{% highlight erb %} +

    <%= notice %>

    +{% endhighlight %} + +This line is not necessary as we've already put the authenticated user notice in the `app/views/layouts/application.html.erb` file. + + +Let's add-commit-push to your GitHub repo! + +### Resource Associations + +Note that places aren't yet properly associated with users. For instance, when creating a new place the field "User" is expected to be filled by ourselves and when viewing a user profile there isn't any list of places created by him/her and viceversa. Also, when deleting a user account all the places he/she created do not get deleted automatically. + +Let's properly create the 1-to-many association between User and Places. + +#### Step 1. Add 1-to-many association + +You need to make sure that Rails knows the relation between the User and Place resources. +As one user can create many places we need to make sure the user model knows that. +Open app/models/user.rb and after the row +{% highlight ruby %} +class User < ActiveRecord::Base +{% endhighlight %} +add +{% highlight ruby %} +has_many :places +{% endhighlight %} + +The place also has to know that it belongs to a user. So open app/models/place.rb and after +{% highlight ruby %} +class Place < ActiveRecord::Base +{% endhighlight %} + +add the row +{% highlight ruby %} +belongs_to :user +{% endhighlight %} + +#### Step 2: Render the views + +Open app/views/places/_form.html and after +{% highlight erb %} +
    + <%= f.label :user_id %>
    + <%= f.number_field :user_id %> +
    +{% endhighlight %} + +add the row +{% highlight erb %} +<%= f.hidden_field :user_id, :value => current_user.id %> +{% endhighlight %} + +next, remove +{% highlight erb %} +
    + <%= f.label :user_id %>
    + <%= f.number_field :user_id %> +
    +{% endhighlight %} + +## Step 3: Set edit/delete permissions + +Allow only the place creator to edit/delete a place. + +Open app/vies/places/index.html.erb and substitute + + +{% highlight sh %} +
    + +{% endhighlight %} + +with + + +{% highlight sh %} + <% if user_signed_in? %> + <% if current_user.id == place.user_id %> + + + + <% end %> + <% end %> +{% endhighlight %} + +That's it. Now view a user you have inserted to your application and there you should see the form for creating a place as well as deleting older places. + + + + +## Place's Comments + +Just as well as we created a "place" resource and associated it with users, we can create a "comment" resource and associate it with places 9and with its author). + +
    +
    +{% highlight sh %} +rails generate scaffold comment body:text user_id:integer place_id:integer +bin/rake db:migrate +{% endhighlight %} +
    +Start the server, check out the new service in your browser. Then, add-commit-push to github. +
    + + +**Coach:** show that the scaffold generator has updated the Rails routes file with a rule for the Review resource + + +##Resource Association + +#### Step 1. Add 1-to-many association + +Open app/models/place.rb and after the row +{% highlight ruby %} +belongs_to :user +{% endhighlight %} +add +{% highlight ruby %} +has_many :comments +{% endhighlight %} + +Open app/models/comment.rb and after +{% highlight ruby %} +class Comment < ActiveRecord::Base +{% endhighlight %} + +add the rows +{% highlight ruby %} +belongs_to :user +belongs_to :place +{% endhighlight %} + +#### Step 2: Render the views + +Open app/views/comments/_form.html and substitute +{% highlight erb %} +
    + <%= f.label :user_id %>
    + <%= f.number_field :user_id %> +
    +{% endhighlight %} + +with the row +{% highlight erb %} +<%= f.hidden_field :user_id, :value => current_user.id %> +{% endhighlight %} + +next, substitute +{% highlight erb %} +
    + <%= f.label :place_id %>
    + <%= f.number_field :place_id %> +
    +{% endhighlight %} + +with the row +{% highlight erb %} +<%= f.hidden_field :place_id%> +{% endhighlight %} + + + + + +Open app/views/places/show.html.erb and just before the bottom links add +{% highlight erb %} +

    Comments

    +<% @comments.each do |comment| %> +
    + <%= comment.user_id %> +
    +

    <%= comment.body %>

    +

    <%= link_to 'Delete', comment_path(comment), method: :delete, data: { confirm: 'Are you sure?' } %>

    +
    +<% end %> +<%= render 'comments/form' %> +{% endhighlight %} + +In app/controllers/places_controller.rb add to show action after the row +{% highlight ruby %} +@place = Place.find(params[:id]) +{% endhighlight %} + +this +{% highlight ruby %} +@comments = @place.comments.all +@comment = @place.comments.build +{% endhighlight %} + + + + + +## Step 3: Set edit/delete permissions + +Allow only the comment creator to edit/delete a comment. + +Open app/views/places/show.html.erb and substitute + + +{% highlight sh %} +

    <%= link_to 'Delete', comment_path(comment), method: :delete, data: { confirm: 'Are you sure?' } %>

    +{% endhighlight %} + +with + + +{% highlight sh %} + <% if user_signed_in? %> + <% if current_user.id == comment.user_id %> + +

    <%= link_to 'Delete', comment_path(comment), method: :delete, data: { confirm: 'Are you sure?' } %>

    + + <% end %> + <% end %> +{% endhighlight %} + + + + + +## Resource Field Validation + +At the moment comments, places and users are characterized by information that is never validated for its correctness. Still, for instance, there should be a limit on the length of comments in review or on the format of a user's email address. + + +Then let's add a constraint over the length of the comment's body field (we'll use the 'validates' keyword). +Open app/models/comment.rb and add between 'class' and 'end': + +
    +
    +{% highlight sh %} + validates :body, length: { maximum: 140 } +{% endhighlight %} +
    +If we now try to enter more than 140 characters we'll get an error. (try it out! ;) ) +
    + +## Finetune the routes + +If you try to open [http://localhost:3000](http://localhost:3000) it still shows the "Welcome aboard" page. Let's make it redirect to the places page. + +Open `config/routes.rb` and after the first line add + +{% highlight ruby %} +root :to => redirect('/places') +{% endhighlight %} + +Test the change by opening the root path (that is, http://localhost:3000/) in your browser. + +**Coach:** Talk about routes, and include details on the order of routes and their relation to static files. + +**Rails 3 users:** You will need to delete the index.html from the `/public/` folder for this to work. + + + diff --git a/_posts/2014-05-29-touristic-autism_resource-rating.markdown b/_posts/2014-05-29-touristic-autism_resource-rating.markdown new file mode 100644 index 00000000..16cf467d --- /dev/null +++ b/_posts/2014-05-29-touristic-autism_resource-rating.markdown @@ -0,0 +1,85 @@ +--- +layout: default +title: Touristic Autism-friendly Spots App +permalink: touristic-autism_resource-rating +--- + +# Resource Rating + +*Created by Myriam Leggieri, [@iammyr](https://twitter.com/iammyr)* +*for [Rails Girls Galway](https://github.com/RailsGirlsGalway)* +The basic guides that have been merged and adapted are the [Ruby on Rails Tutorial](http://www.railstutorial.org/book), the [basic RailsGirls app](http://guides.railsgirls.com/app/) and the tutorials for [creating thumbnails](http://guides.railsgirls.com/thumbnails), [authenticating users](http://guides.railsgirls.com/devise/), [adding design](http://guides.railsgirls.com/design), [deploying to OpenShift](http://guides.railsgirls.com/openshift/) and [adding comments](http://guides.railsgirls.com/commenting). + +What do we want our app to do? As a first thing, we would like to +* authenticate **users** +* allow authenticated users to create a new touristic **place** description +* allow authenticated users to **comment** those places +* allow authenticated users to **rate** up to which extent those places are autism-friendly or not. + +We modeled and deployed comment, user and place resources, so far. Let's now enable the rating for places. + +## Rating Places + +## Step 0: Add letsrate gem + +Open up your `Gemfile` and add this line + +{% highlight ruby %} +gem "letsrate", :git => "git://github.com/iammyr/letsrate.git" +{% endhighlight %} +and run +{% highlight sh %} +bundle install +{% endhighlight %} +to install the gem. **Also remember to restart the Rails server**. + +## Step 1: Set up letsrate in your app + +Run the following command in the terminal. (we are assuming that we had already enabled authenticated users using the devise gem) + +{% highlight sh %} +rails g letsrate user +{% endhighlight %} + +## Step 2: Apply letsrate to your resource + +You should add the letsrate_rateable function with its dimensions option, to the model of the resource you wish to rate, i.e., place. You can have multiple dimensions. + +In app/models/place.rb add + +{% highlight sh %} + letsrate_rateable "autism_friendly", "overall" +{% endhighlight %} + +Then you need to add a call letsrate_rater in the user model: + +{% highlight sh %} + letsrate_rater +{% endhighlight %} + +## Step 3: Render the Views + +There is a helper method which name is rating_for to add the star links. By default rating_for will display the average rating and accept the new rating value from authenticated user. + +Open app/views/places/show.html.erb and add + +{% highlight sh %} +

    +Votes:
    +Autism_friendly : <%= rating_for @place, "autism_friendly" %>
    +Overall : <%= rating_for @place, "overall" %> +

    +
    +

    +Your votes:
    +Autism_friendly : <%= rating_for_user @place, current_user, "autism_friendly", :star => 7 %> +Overall : <%= rating_for_user @place, current_user, "autism_friendly", :star => 7 %> +

    +
    +{% endhighlight %} + +You can use the rating_for_user helper method to show the star rating for the user. + + +That's it! ^__^ +Try it out by restarting the server, add, commit and push on GitHub. If all it's working then you can also deploy ;) diff --git a/_posts/2014-05-29-touristic-autism_static-pages-tdd.markdown b/_posts/2014-05-29-touristic-autism_static-pages-tdd.markdown new file mode 100644 index 00000000..0b81282b --- /dev/null +++ b/_posts/2014-05-29-touristic-autism_static-pages-tdd.markdown @@ -0,0 +1,272 @@ +--- +layout: default +title: Touristic Autism-friendly Spots App +permalink: touristic-autism_static-pages-tdd +--- + +# Test-Driven Development + +*Created by Myriam Leggieri, [@iammyr](https://twitter.com/iammyr)* +*for [Rails Girls Galway](https://github.com/RailsGirlsGalway)* +The basic guides that have been merged and adapted are the [Ruby on Rails Tutorial](http://www.railstutorial.org/book), the [basic RailsGirls app](http://guides.railsgirls.com/app/) and the tutorials for [creating thumbnails](http://guides.railsgirls.com/thumbnails), [authenticating users](http://guides.railsgirls.com/devise/), [adding design](http://guides.railsgirls.com/design), [deploying to OpenShift](http://guides.railsgirls.com/openshift/), [adding comments](http://guides.railsgirls.com/commenting) and [Mark McDonnell's tutorial] (http://code.tutsplus.com/tutorials/testing-your-ruby-code-with-guard-rspec-pry--cms-19974). + +Rails includes a default Test::Unit framework used to test your code. We will use a more advanced testing framework called RSpec to write a thorough test suite. We need to be able to write tests that are fast and give us instant feedback on problems with our code. + +We will use Guard and RSpec to monitor some of our files and run tests over them as soon as they get modified, so to be sure that the latest changes are not breaking the app anywhere. + +If any error is found, then we are going to dig into it so to understand the cause and fix it, by using Pry. + +Finally, since we are assuming to be developing in collaboration with other via GitHub, we will also make sure that each contribution does not conflit when integrating with the others' ones. For this very reason, we will also commit, push and test the integration often, in a process called "Continuous Integration". We will use Travis-CI to support us. + +##Continuous testing with Guard + +In your Gemfile, add + +{% highlight sh %} +group :test do + gem 'rspec' +end + +group :development do + gem 'guard' + gem 'guard-rspec' +end +{% endhighlight %} + +Then run "bundle install". Then create a file called Rakefile in your main project directory and add + +{% highlight sh %} +require 'rspec/core/rake_task' + +RSpec::Core::RakeTask.new do |task| + task.rspec_opts = ['--color', '--format', 'doc'] +end +{% endhighlight %} + +When you install RSpec, it gives you access to a built in Rake task and that's what we're using here. We create a new instance of RakeTask which by default creates a task called spec that will look for a folder called spec and will run all the test files within that folder, using the configuration options we've defined (here color and format of the test output on the command line). + +Note: to run the tests just enter "rake spec" in your command line. You'll get zero failures because we haven't written either any test or any code, yet. + +Now add the following to a new file (in your main project directory) called "Guardfile": + +{% highlight sh %} +guard 'rspec' do + # watch /app/views files + watch(%r{^app/views/(.+).html.rb$}) do |m| + "spec/features/#{m[1]}_spec.rb" + end + +# watch /spec/ files + watch(%r{^spec/features/(.+).rb$}) do |m| + "spec/features/#{m[1]}.rb" + end +end +{% endhighlight %} + +The contents of this file tells Guard what to do when we run the guard command. + +If we ran guard rspec then Guard would watch the specified files and execute the specified commands once any changes to those files had occurred. Note: because we only have one guard task, rspec, then that is run by default if we ran the command guard. + +In this instance, we're telling Guard to watch all the files within our app/views and spec/features folders and if any changes occur to any of those files then to execute the test files within our spec/features folder to make sure no changes we made broke our tests (and subsequently didn't break our code). + +Now, as in proper Test-Driven Development(TDD), let's create a test for our static "Home" page, before we even create the Home page. + +We're going to create a file titled home_spec.rb and place it in the spec/feature folder (as this is what we told Guard to expect). The purpose of this file is to become our specification file (in other words, this is going to be our test code and will represent the expected functionality). + +Note: in Ruby the words "test" and "specification" are often considered interchangable. + +###TDD: Writing Test Code Before Application Code + +Typically, if you write your application code first (so you're not doing TDD), then you will find yourself writing code that at some point in the future is over engineered and potentially obsolete. Through the process of refactoring or changing requirements, you may find that some functions will fail to ever be called. + +This is why TDD is considered the better practice and the preferred development method to use, because every line of code you will produce has been produced for a reason: to get a failing specification (your actual business requirement) to pass. + +Let's write the test "home.html.erb_spec.rb as: + +{% highlight sh %} +require 'spec_helper' + +describe "test for the static page Home" do + it "displays the text attribute of the message" do + render + rendered.should contain("Hello world!") + end +end +{% endhighlight %} + + +To help us reduce the boilerplate code, we'll place it inside of a special helper file that we'll load from our specification files. This file will be titled spec_helper.rb. + +This file will do a couple of things: + +* tell Ruby where our main application code is located +* load our application code (for the tests to run against) +* load the pry gem (helps us debug our code; if we need to). + +Here is the code: + +{% highlight sh %} +$ << File.join(File.dirname(FILE), '..', 'app/views') + +require 'pry' +require 'home' +{% endhighlight %} + + +Let's open a new command line, enter "guard" and leave it running: it will monitor our views in app/views and run tests from spec/features against them. If we now create an empty file "app/views/home.html.erb" guard will run the test and the test will unsurprisingly fail. + +The point of TDD is to have a tight feedback loop, also known as 'red, green, refactor'). What this means in practice is: + +* write a failing test +* write the least amount of code to get it to pass +* refactor the code + +The error is telling us that... + + + +Then let's create our static page Home. We create a PagesController whose purpose is to deal with static pages (e.g., Home, About, Help). Each page is represented by one action in the controller "pages_controller.rb". + +{% highlight sh %} +class PagesController < ApplicationController + def home + end + + def about + end + + def help + end +end +{% endhighlight %} + +Now we have to tell the server to match the browser requests for each different page to our actions: + +{% highlight sh %} +match '/home' => 'pages#home' +match '/about' => 'pages#about' +match '/help' => 'pages#help' +{% endhighlight %} + +We then create home.html.erb, about.html.erb, and hrlp.html.erb views under app/views/pages. These views contain whatever content you want on your static pages. They'll by default use your app's application.html.erb layout. + +For now, we'll leave them empty and only add the following to home.html.erb, in order to satisfy our test. + +{% highlight sh %} +Hello world! +{% endhighlight %} + +Now, if we check the command line window where "guard" was running, we'll see it automatically did run our test as soon as we saved the changes to our home.html.erb file, and that the test is now succeeding. + +*Note:* if we wanted to run the test manually rather than via Guard, we would have had to run "rspec spec/features/home.html.erb_spec.rb" + + +## Debugging with Pry + +For the purpose of demonstrating Pry we are going to add more code to our controller (this extra code doesn't effect our test in any way). + +{% highlight sh %} +class PagesController < ApplicationController +attr_accessor :test + + @@class_property = "I'm a class property" + + def home + binding.pry + @instance_property = "I'm an instance property" + pubs + privs + "Hello RSpec!" + end + + def about + test_var = "I'm a test variable" + test_var + end + + def help + end + + private + + def privs + puts "I'm private" + end +end +{% endhighlight %} + +A break-point is a place within your code where execution will stop. +You can have multiple break-points set within your code and you create them using "binding.pry" (note it's been included above). + +When you run your code you'll notice that the terminal will stop and place you inside your application's code at the exact spot your binding.pry was placed. + +From this point Pry has access to the local scope. You can type "exit" to exit Pry and for your code to continue executing. + +**Note:** Try finding where you are: (by typying) whereami; Stack Trace: wtf; Inspecting (available methods and properties): ls; Changing Scope: cd. + +##Continuous Integration (CI) with Travis-CI + +The principle of CI is to commit/push early and often to avoid conflicts between your code and the master branch. When you do (in this case we're committing to GitHub) then that should kick off a 'build' on your CI server which runs the relevant tests to ensure all is working as it should be. + +Travis CI is a hosted continuous integration service for the open source community. It offers free CI services for open-source projects and also has a paid model for businesses. We'll be using the free open-source model on our GitHub repository. + +The process is this: + +* Sign into Travis-CI using your GitHub account +* Go to your "Accounts" page +* Turn "on" any repositories you want to run CI on +* Create a .travis.yml file within the root directory of your project and commit it to your GitHub repository + +The .travis.yml file determines the configuration settings for Travis-CI so it knows how to handle running the tests for your project. Let's create it as follows: + +{% highlight sh %} +language: ruby +cache: bundler + +rvm: + - 1.25.26 + +script: 'bundle exec rake spec' + +bundler_args: --without development + +branches: + only: + - master + +notifications: + email: + - you@example.com +{% endhighlight %} + +We need to add "gem 'rake'" to our Gemfile within the ":test" group, as this is a requirement of Travis-CI. + +Travis-CI uses RVM (Ruby Version Manager) for installing Rubies on their servers. So we need to specify what Ruby versions we want to run our tests against. + +Also, let's add to spec/spec_helper.rb the following: +{% highlight sh %} + require 'pry' if ENV['APP_ENV'] == 'debug'" +{% endhighlight %} + +and make clear in our Gemfile which gems are required for testing and which for development: + +{% highlight sh %} +group :test do + gem 'rake' + gem 'rspec' +end + +group :development do + gem 'guard' + gem 'guard-rspec' + gem 'pry' + + # Adds debugging steps to Pry + # continue, step, next + gem 'pry-remote' + gem 'pry-nav' +end +{% endhighlight %} + +**Note:** if you have any issues regarding Travis-CI then you can join the "#travis" channel on IRC freenode to get help answering any questions you may have. +
    <%= place.picture %><%= image_tag place.picture_url(:thumb) if place.picture? %><%= link_to 'Edit', edit_place_path(place) %><%= link_to 'Destroy', place, method: :delete, data: { confirm: 'Are you sure?' } %><%= link_to 'Edit', edit_place_path(place) %><%= link_to 'Destroy', place, method: :delete, data: { confirm: 'Are you sure?' } %>