Archive for category Ruby and Rails
Rails – File, New Project…
Posted by John in Ruby and Rails on January 19, 2011
Even with RubyMine starting a new project is not simply File, New Project, like the rails new command, it can only take you so far.
It’s not complicated to set up a new Rails project but, as something you are likely to do farily infrequently, it is easy to skip or forget steps or commands. Charles Max Wood has posted a screencast of his Rails set up at what looks to be the start of a great screencast series.
Here is a terse run down of my setup:
rails new appname -J -T-J skips prototype files, -T skips testunit files.cd appnamervm --create --rvmrc 1.9.2@appnamervm rvmrc trustmvim .or mate . or whatever editor you use.- Amend the /Gemfile (Edit: I’ll update these files as I improve my process, add new gems to the default set and gems are updated/changed)
bundle installrails g rspec:installrails g cucumber:install --capybara --rspec --sporkspork --bootstraprails g jquery:install -uirake db:create- Amend /.gitignore
git flow initAccept the git-flow defaults. I like the structure provided by git-flow and will post on it in the future to explore it more.git add .git commit -m "Project skeleton"git remote add origin git@github.com:JohnPlummer/project_name.gitgit push -u origin developgit push -u origin master
Managing Ruby Gems
Posted by John in Ruby and Rails on December 29, 2010
Ruby gems are packages that add functionality to the core Ruby libraries. Each gem normally provides functionality in a specific area and can depend on other gems. Rails is a Ruby gem. Presumably, in the past, gem versioning caused problems for Ruby devs which has led to the development of a couple of tools:
RVM
RVM stands for Ruby Version Manager and allows a dev to switch betwen versions of Ruby. More importantly it can also sets of gems.
- Gemsets are associated with a particular version of Ruby.
- There is gemset named global (per Ruby version) and gems in this set are available to all other gemsets for that Ruby version.
- To associate a project with a particular gemset, include a .rvmrc file in the project root containing
rvm –create use version@project_name > /dev/null
This will create the gemset if it does not exist and switch to it automatically. - Useful commands to work with gemsets: rvm gemset [list|name|create|use|delete|empty|rename|copy]
Bundler
While RVM is used to manage and switch between installed gems, Bundler is a tool to install gems and associate them with a project.
- Bundler is itself a gem and is installed with Rails 3.
- Project dependencies are listed in a gemfile file in the project root.
- Gems versions can be specified in the gemfile but that is not really necessary with the gemfile.lock file which stores version numbers.
- bundle install ensures all gems listed in the gemfile are installed to the current gemset.
- Gems can be grouped by environment (development | test | production).
- Bundler ensures that the correct gems are ‘required’ by Ruby for the environment it is running under.
- The environment groups allow bundle install to be selective on what to install. e.g. for a production server
bundle install –without development test
RubyMine Gem Management
It looks as though RubyMine will be my environment of choice and it includes it’s own sdk (Ruby version) and gem management system that should integrate well with RVM’s gemsets and Bundler’s gemfile.
- A project can be associated with a particular version of Ruby and a gemset in RM’s settings pane.
- Once a gemset is selected, any gems installed by RM will be installed to this gemset.
- RM should also be able to read a .rvmrc file in the project root and switch automatically to the specified gemset. This currently (RM 3.0.1) seems not to work with newly created gemsets that have not yet had gems installed to them so best to check in the project settings to be sure.
- RM scans the gemfile, offering to install and attach and missing gems.
- Gems that are attached get scanned by RM to enable features such as autocomplete within the IDE.
Rails and Rake Commands and Rails Environments
Posted by John in Ruby and Rails on December 23, 2010
Rails
Rails seems to consist of two parts, a set of components to build an application on top of and a command line tool to help this process. The reason the rails command is so useful is the amount of convention in a Rails app: Certain files with certain names are expected in certain locations. When one file or class is created, the chances are that a number of further files and classes will be required. The most commonly used rails commands are:
rails new
The first command is rails new app_name. This can take a number of options to specify versions, templates, databases, or to skip certain parts of the application. View a full list with rails new –h. Rails new appname –t is possibly useful to skip creating the test folder if you intend to use rspec.
rails server
Runs the default rails dev server, WEBrick. which can be viewed on localhost:3000. Again use –h to view all the options. The –d option runs the server as a daemon and –u enables debugging. One option to be aware of is –e which allows you to specify an environment to run under, more on this later. rails s can be substituted for rails server.
rails generate
Creates boilerplate code for various parts of an application. Installing a gem (such as rspec) can add additional generators. The most common rails generators are probably scaffold, model, controller and migration. rails g can be used in place of rails generate.
- rails g controller controller_name action1 action2 … generates a controller with the specified actions and views to match the actions. e.g. rails generate controller Products buy sell will create app/controllers/products_controller.rb which will contain class ProductsController with methods buy and sell. It will also create the views app/views/products/buy.html.erb and app/views/products/sell.html.erb. The command will also create routes, test classes and helpers.
- rails g model model_name field1:type field2:type … creates a class for the model in app/models/model_name.rb and a database migration file to add a matching table to the database. It also creates a test class and a fixture file (to provide test data).
- rails g migration migration_name creates a migration file with the specified name (preceded by a timestamp). To add colums to an existing table rails g migration add_something_to_tablename field1:type field2:type can be used to create the correct migration automatically.
- rails g scaffold model_name field1:type field2:type … Combines all of the above, creating a model and migration, a controller with basic CRUD actions, matching views, tests, helpers etc. Although this would appear useful it is meant to be more of a learning tool (and useful for the various instant gratification demo’s of Rails).
rails console
Starts a console that can run ruby code. Like the rails server an environment can be specified to run under e.g. rails console test (note this is different to rails server).
Rake
Rake is a ruby command for ‘ruby make’ used for common administration tasks. The most common tasks are to administer databases and run tests.
rake test
Runs the applications tests, a number of options can be used to restrict the tests that are run.
rake db:command
There are a number of db commands but the most used is db:migrate. This command can take further options, one of which is used to specify the rails environment – rake db:migrate RAILS_ENV=test (and a third syntax to specify the environment.
Environments
After running rails new appname, three environments will be available, development, production, and test. The settings for the environments are specified in config/environments /*.rb and as seen above, various commands can specify the environment they run under. Further environments can be created if required e.g. staging.
The default environment for rails server, console and rake db:migrate is development. Tests run in the test environment. Running under other environments is normally done by specifying the environment in the server or hosting configuration.
The rails environment is useful in a number of other places such as:
Testing the environment from code -
<%= debug(params) if Rails.env.development? %>
Loading certain gems for specific environments with groups in the gemfile
source 'http://rubygems.org' gem 'rails', '3.0.3' gem 'sqlite3-ruby', '1.2.5', :require => 'sqlite3' gem 'gravatar_image_tag', '0.1.0' group :development do gem 'rspec-rails', '2.1.0' gem 'annotate-models', '1.0.4' end group :test do gem 'rspec', '2.1.0' gem 'webrat', '0.7.1' gem 'autotest', '4.3.2' gem 'autotest-fsevent', '0.2.2' gem 'autotest-growl', '0.2.8' gem 'autotest-rails-pure', '4.1.0' gem 'spork', '0.8.4' gem 'factory_girl_rails', '1.0' end
Learning Ruby: First Impressions
Posted by John in Ruby and Rails on December 17, 2010
Ruby (and Rails) seem to be designed to make the code look very like natural language. This makes the code very easy to read but less easy (for someone new to Ruby) to write. It seems like there is a lot you are required to know, although maybe a Ruby programmer looking at CSharp for the first time would think that there is a lot to know?
There are a lot of conventions in Ruby, the most obvious is that method names are all lower case with words separated by underscores. Combine this with other syntax such as brackets surrounding method parameters are optional, ‘unless’ being the inverse of ‘if’, and allowing the if (or unless) statement to be placed after the statement that is to run if it is one line and you get code that looks very close to natural language.
if(!user.Authorized)
RedirectTo(rootPath);
becomes
redirect_to root_path unless user.authorized?
The next things that strike you are the use of symbols and hashes, they seem to appear everywhere.
Symbols are similar to global constants in other languages, except they do not have to be declared and they aren’t assigned a value. A symbol is a colon followed by a name (:red, :monday, :ford etc). Ruby assigns a value to the symbol behind the scenes and this value will match wherever it is used in a program.
A common use of symbols is as keys for hashes. Hashes are declared as a number of key value pairs enclosed in braces. The key and value are separated by ‘=>’.
week = {
:sunday => 'weekend',
:monday => 'workday',
:tuesday => 'workday'
...
}
Hashes are often used to pass a variable number of parameters to a method:
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => { :case_sensitive => false }
Two things to note with this common pattern:
- If the hash is the last parameter in the method definition, it doesn’t require curly braces around it.
- The value of a hash item can be another hash (and this should have braces).
Code blocks are chunks of code surrounded by either braces or do … end and don’t appear too different from CSharp’s anonymous methods. A code block can be passed to a normally defined method and the yield keyword used to run the code block, passing parameters if needed.
This is only a first pass, but Ruby doesn’t look too far from CSharp. I haven’t mentioned the obvious difference that Ruby is dynamic but I doubt anyone would be ‘surprised’ by that.
Learning Ruby (on Rails)
Posted by John in Ruby and Rails on December 15, 2010
Most of my programming career has revolved around Microsoft technologies, starting with Visual Basic 3, up through the various versions to VB.Net, then switching to CSharp shortly after DotNet came out of beta.
I think I know the MS development stack fairly well and I like the direction they are moving in with the likes of MVC3 and Razor, Nuget etc. but it seems a fair amount of this ‘direction’ may be coming from the Rails community.
I have decided to give myself 2 weeks to ‘learn’ Rails, although I may get distracted by the Christmas holidays (and the fact that we will have an extra 6 kids and 3 adults staying with us for 2 weeks) and will record some of it here.
I have done a little research in preparation and bought a couple of ebooks from the prags:
They seem to be considered ‘definitive’ and cover the current versions of Rails (3.0.3) and Ruby (1.9.2).
The only other purchase I am likely to make is an IDE or editor. I code on a Mac, even when using Visual Studio so I have a few more options than most Windows users. The recommendation seems to be that, if you are on Windows, install a Linux VM for Ruby development. The favourite environment for the Mac looks to be Textmate although there are a few IDEs available such as JetBrain’s RubyMine and Aptana Studio, both of these are available for Windows, OS x, and Linux. I am a fan of JetBrain’s Resharper so will try RubyMine, the trial is 30 days so no need to make a purchase decision yet.
Other references that I expect to find useful over the next 2 weeks are: