Best ruby-on-rails questions in December 2010

Why doesn't Rails' "errors.full_messages" replace attribute and message variables?

13 votes

Having a strange problem with a rails model I just created.

Here are my validations:

validates_presence_of :from_name, :message => 'Please provide a from name.'
validates_presence_of :from_email
validates_presence_of :giftition_plan_id

I'm having issues using errors.full_messages as well as f.error_messages in my form:

g = Giftition.create
g.errors.first
=> ["from_name", "Please provide a from name."]
>> g.errors.full_messages
=> ["{{attribute}} {{message}}", "{{attribute}} {{message}}", "{{attribute}} {{message}}"]

I'm just getting "{{attribute}} {{message}}". Any ideas?

UPDATE: I've uninstalled rails 3 and all the gems that were installed with it and that made the problem go away. It's not a fix though... I would still like to have rails 3 installed.

UPDATE: Sounds like upgrading to 2.3.9 fixes the problem. Unfortunately, I've given up for now, but sometime in the future I will try that.

Upgrading to Version rails 2.3.9 fixes this problem

gem install -v 2.3.9 rails --include-dependencies

EDIT:

You also need to edit the config\environment.rb file to change the RAILS_GEM_VERSION.

RAILS_GEM_VERSION = '2.3.9'

EDIT #2:

I should note that version 2.3.9 is not the latest version of the 2.3.X branch, and you should upgrade the the latest version available.

How to test Rails 3 Engines with Cucumber & Rspec?

12 votes

I apologize if this question is slightly subjective... I am trying to figure out the best way to test Rails 3 Engines with Cucumber & Rspec. In order to test the engine a rails 3 app is necessary. Here is what I am currently doing:

  1. Add a rails test app to the root of the gem (myengine) by running: rails new /myengine/rails_app

  2. Add Cucumber to /myengine/rails_app/features as you would in a normal Rails app

  3. Require the Rails Engine Gem (using :path=>"/myengine") in /myengine/rails_app/Gemfile

  4. Add spec to the root directory of the gem: /myengine/spec

  5. Include the fixtures in /myengine/spec/fixtures and I add the following to my cuc env.rb:

env.rb:

Fixtures.reset_cache
fixtures_folder = File.join(Rails.root, 'spec', 'fixtures')  
fixtures = Dir[File.join(fixtures_folder, '*.yml')].map {|f| File.basename(f, '.yml') }  
Fixtures.create_fixtures(fixtures_folder, fixtures)

Do you see any problems with setting it up like this? The tests run fine, but I am a bit hesitant to put the features inside the test rails app. I originally tried putting the features in the root of the gem and I created the test rails app inside features/support, but for some reason my engine would not initialize when I ran the tests, even though I could see the app loading everything else when cuc ran.

If anyone is working with Rails Engines and is using cuc and rspec for testing, I would be interested to hear your setup.

**UPDATE
I changed my setup a bit since I wrote this question. I decided to get rid of the spec directory under the root of the engine. Now I just create a rails app named "test_app" and setup cuc and rspec inside that app like I would normally do in a rails app. Then I include the gem like I did in step #3 above. Since the engine is a sub-app, I guess its just best to test it like it was a normal rails app. I am still interested in hearing if anyone has a different setup.

Rails 3.1 (will) generate a pretty good scaffold for engines. I'd recommend using RVM to create a new gemset called edge and switch to it:

rvm gemset create edge
rvm use @edge

Then install edge rails:

git clone git://github.com/rails/rails.git
cd rails
rake install

From there, you can follow Piotr Sarnacki's mountable app tutorial, replacing calls such as:

bundle exec ./bin/rails plugin new ../blog --edge --mountable

With simply:

rails plugin new blog --mountable --full

The mountable option makes the application mountable, whilst the full option makes it an engine with tests already built-in. To test the engine, this generator generates a folder in test called dummy which contains a small Rails application. You can see how this is loaded in test/test_helper.rb.

Then it's up to you to massage the data to do what it needs to in order to work. I would recommend copying over the cucumber files from a standard rails g cucumber:install into the project and then messing about with it until it works. I've done this once before so I know it's possible, but I cannot find the code right now.

Let me know how you go.

Please recommend me some rails/ruby open source code that needs documentation/tests written

11 votes

I've been using ruby on rails for the last 4 months or so and I've been really enjoying the whole concept of open source. I know it's not exclusive to ruby/rails but coming from windows programming this is my first real exposure to it.

I want to "give back" what I can but I don't feel like I can contribute any worthwhile open source projects or gems of my own. So I figured a good place to start is by documenting or writing tests for some existing projects.

Could you guys please point me to a few possible options? I'd prefer projects that are pretty active but at the same time not too complex (since I'm not very good with ruby right now).

This might be a subjective question but at this point I have no idea where to even start. So even subjective answers would be much appreciated.

Kudos! There are several ways to participate.

I think the question to ask yourself is, what are your areas of expertise? What subject area to you have a solid knowledge of? For example, if you had experience with Web Services, the Savon project is in dire need of documentation, examples, etc. If you have Java experience, there are many burgeoning JRuby projects that could use a hand.

You can check the Ruby Toolbox, which lists gems in categories by popularity. Look in the areas that appeal to you and check out the popular gems. The vast majority of gems have github repositories. If you haven't learned git, I highly recommend it. It's super easy to branch a project, update it. Look for projects which have a good test suite, which will not only help you figure out how it works, but will give you good examples for testing your additions/fixes.

Also, the Ruby and Rails documentation at APIdock allows for comments. If you come across something that's not entirely clear in the Rails documentation, for example, you can add a clarifying comment or examples.

Tired of non-semantic testing to make up for dynamic typing - suggestions?

9 votes

I used to do a lot of web programming in Rails (PHP before that) before I started studying computer engineering.

Since then, I've done a lot of school work in C, and some personal stuff in Objective-C (Mac stuff). I learnt to love static typing.

But now I'm having to do some professional web development (freelancing) and have picked up Rails once again. I'm finding it really annoying to write non-semantic type-checking tests. I was getting those for free from C and Objective-C compilers. I loved hitting Build and having the system check all my code to see that A can call B, B can call some obscure library C, etc. All I had to do was test the semantics. But with Rails, I'm the compiler. :(

Has anyone treaded this same path? Are my only options for web development ASP.NET MVC with C# and Java + x framework? Looking for some suggestions, or even some sympathy... :P

By the way, I make a specific reference to Rails rather than Ruby because I don't mind Ruby's dynamic nature for simple stuff like scripting or what not. But since Rails depends on so many gems and since one usually adds a number of other gems, the dynamic typing becomes an issue.

Thanks!

edit:

I followed up on pst's suggestion and looked into Scala. In reading the book Programming in Scala, written by the language's creator, Martin Odersky, I came accross this bit of text that in many ways expresses my concerns and a bit more. Very interesting reading.

Taken from page 52 of Martin Odersky's Programming in Scala:

Scala is statically typed

A static type system classifies variables and expressions according to the kinds of values they hold and compute. Scala stands out as a language with a very advanced static type system. Starting from a system of nested class types much like Java’s, it allows you to parameterize types with generics, to combine types using intersections, and to hide details of types using abstract types. These give a strong foundation for building and composing your own types, so that you can design interfaces that are at the same time safe and flexible to use.

If you like dynamic languages such as Perl, Python, Ruby, or Groovy, you might find it a bit strange that Scala’s static type system is listed as one of its strong points. After all, the absence of a static type system has been cited by some as a major advantage of dynamic languages. The most common arguments against static types are that they make programs too verbose, prevent programmers from expressing themselves as they wish, and make impossible certain patterns of dynamic modifications of software systems.

However, often these arguments do not go against the idea of static types in general, but against specific type systems, which are perceived to be too verbose or too inflexible. For instance, Alan Kay, the inventor of the Smalltalk language, once remarked: “I’m not against types, but I don’t know of any type systemsthat aren’t a complete pain, so I still like dynamic typing.”

We hope to convince you in this book that Scala’s type system is far from being a “complete pain.” In fact, it addresses nicely two of the usual concerns about static typing: verbosity is avoided through type inference and flexibility is gained through pattern matching and several new ways to write and compose types. With these impediments out of the way, the classical benefits of static type systems can be better appreciated. Among the most important of these benefits are verifiable properties of program abstractions, safe refactorings, and better documentation.

Verifiable properties

Static type systems can prove the absence of certain run-time errors. For instance, they can prove properties like: booleans are never added to integers; private variables are not accessed from outside their class; functions are applied to the right number of arguments; only strings are ever added to a set of strings.

Other kinds of errors are not detected by today’s static type systems. For instance, they will usually not detect non-terminating functions, array bounds violations, or divisions by zero. They will also not detect that your program does not conform to its specification (assuming there is a spec, that is!). Static type systems have therefore been dismissed by some as not being very useful. The argument goes that since such type systems can only detect simple errors, whereas unit tests provide more extensive coverage, why bother with static types at all?

We believe that these arguments miss the point. Although a static type system certainly cannot replace unit testing, it can reduce the number of unit tests needed by taking care of some properties that would otherwise need to be tested. Likewise, unit testing cannot replace static typing. After all, as Edsger Dijkstra said, testing can only prove the presence of errors, never their absence. So the guarantees that static typing gives may be simple, but they are real guarantees of a form no amount of testing can deliver.

Safe refactorings

A static type system provides a safety net that lets you make changes to a codebase with a high degree of confidence. Consider for instance a refactoring that adds an additional parameter to a method. In a statically typed language you can do the change, re-compile your system and simply fix all lines that cause a type error. Once you have finished with this, you are sure to have found all places that need to be changed. The same holds for many other simple refactorings like changing a method name, or moving methods from one class to another. In all cases a static type check will provide enough assurance that the new system works just like the old.

Documentation

Static types are program documentation that is checked by the compiler for correctness. Unlike a normal comment, a type annotation can never be out of date (at least not if the source file that contains it has recently passed a compiler). Furthermore, compilers and integrated development environments can make use of type annotations to provide better context help. For instance, an integrated development environment can display all the members available for a selection by determining the static type of the expression on which the selection is made and looking up all members of that type.

This is one of my "gripes" about dynamic languages. I want to test for semantics, not type errors ;-) That being said, a good testing framework/setup is really a must in all non-trivial situations and good code-coverage and tested requirements is/are important.

If you do want to go down the static-typing path on the JVM (I have), I would highly recommend looking at Scala. Coming from Ruby, it's far less painful (and actually lots of fun in different ways) than going to Java. You get to "keep" the things you take for granted -- an expression-based syntax, closures, the ability to omit types in many places (not as open as Ruby, but you do get compile-time type checking ;-), everything(*)-is-an-object OO, unified accessor methods, ability to construct DSLs easily, and sugar -- and get the benefits of a statically typed language with local type inference, pattern matching, a relatively rich collection framework, and decent integration with Java (including the numerous web-frameworks, there are some Scala-specific frameworks as well which leverage the Scala language).

C#3.0/4.0 (and .NET3.5+) isn't too shabby either (but avoid C#2.0, which is now hopefully a relic), with the introduction of LINQ/closures, basic type inference and other nice language features I find it "acceptable" for most tasks (take a guess how I would rate Java as a language ;-). However, C# is a CLR-target language (there is/was a .NET Scala port, but I am not sure of the status -- it is not the main target platform though).

Since I have mentioned Scala, I should also mention F# (now an "official" .NET language) which takes the "Funtional with OO" approach being similar to OCaml -- Scala is more of the reverse and I would describe it as "OO with Functional". I have heard arguments for/against F# compared to C# w.r.t the type system, but have no practical experience with F#. You may or may not like the paradigm shift.

Happy coding.

Turn omniauth facebook login into a popup

9 votes

I'm using the omniauth gem with rails and it works great with loging in users, but everytime it takes you to the fb login page then redirects you back. I was wondering if there is a way to do what most pages do and show the fb login in a popup and then reload the parent div once that is complete. Any ideas?

Thanks!

Sure, you can easily.

In your view:

=link_to "Log in with Facebook", omniauth_authorize_path(:user, :facebook), :class => "popup", :"data-width" => 600, :"data-height" => 400

In your application.js:

function popupCenter(url, width, height, name) {
  var left = (screen.width/2)-(width/2);
  var top = (screen.height/2)-(height/2);
  return window.open(url, name, "menubar=no,toolbar=no,status=no,width="+width+",height="+height+",toolbar=no,left="+left+",top="+top);
}

$("a.popup").click(function(e) {
  popupCenter($(this).attr("href"), $(this).attr("data-width"), $(this).attr("data-height"), "authPopup");
  e.stopPropagation(); return false;
});

And then in your callback view:

:javascript
  if(window.opener) {
    window.opener.location.reload(true);
    window.close()
  }

This'll pop up your Facebook auth in a centered 600x400 popup, then when the user returns from authentication, the view will close the popup and refresh the parent page. It degrades gracefully if a user ctrl-clicks the link, or doesn't have Javascript enabled, too.

Do ruby on rails programmers refactor?

9 votes

I'm a Java programmer who started programming Ruby on Rails one year ago. I like the language, rails itself and the principles behind them. But something that bothers me is that Ruby programmers don't seem to refactor.

I noticed that there is a big lack of tools for refactoring in Ruby / Rails. Some IDE's, like Aptana and RubyMine seem to offer some very basic refactoring, but nothing really big compared to Eclipse's Java refactorings.

Then there is another fact: most railers (even the pros) prefer some lightweight editors, like VIM or TextMate, instead of IDEs. Well, with these tools you just get zero refactoring (only regex with find/replace).

This leaves me this impression that rails programmers don't refactor. It might be just a false impression, of course, but I would like to hear the opinion of people who work professionally with ruby on rails.

Do you refactor? If you do, how do you do it,with which tools? If not, why not?

Yes.

Most Rails programmers try and follow a Test first, write code to pass the test, then refactor the code BEFORE they go onto the next test.

Do ALL rails/ruby programmers... probably not, but as far as a 'vibe' or 'feel' in this community, I'd say it's something that is preached and practiced enough that it happens more times than not.

There is no need for IDEs imo. VIM, emacs and/or textmate is enough for Ruby and most rails programmers. I guess Java needed more compiling or something, what do I know about that though, as I've only programmed in Ruby. Why do all Java programmers use IDEs (since I'm generalizing).

RSpec install error: "Could not find autotest in any of your source paths"

9 votes

When I run:

rails generate rspec:install

I get this output:

   identical  .rspec
       exist  spec
   identical  spec/spec_helper.rb
Could not find "autotest" in any of your source paths. Your current source paths are: 
(..)/rails_projects/sample_app/lib/templates/rspec/install
(..)/rspec-rails-2.3.0/lib/generators/rspec/install/templates

I'm new to RSpec, Rails and Ruby. Any tips on how to make this work?

It's a bug. It can be circumvented:

"A quick solution for those with this problem is to make the missing directory in the gem. (i.e., mkdir rspec-rails-2.3.0/lib/generators/rspec/install/templates/autotest )"

Ref: https://github.com/rspec/rspec-rails/issues/closed#issue/283

How to organize a Rails App

8 votes

hello,

For the first time I'm creating a quite complex Rails app.

I'd like to know what's the best way to organize that app by folders. Until now, I'd do everything under one app (all the models, controllers, etC) but reading some open source code I realize that they put everything under different apps.

Like for example Spree Commerce. They have a general folder and inside that they have different apps (API, core, admin, etc). How is that done and is that the best way to do it?

I'd like to get pointed to the best way to do it (a book, blog, anything) so I can understand how I can architect my app for future maintenance.

thank you

As an aside I think the title of your question is a little confusing. Rails, by using convention over configuration, defines 'how to organise a Rails app'. I think your question is rather about how to architect your application as opposed to anything Rails-specific. Maybe tweak the title?

That aside, without knowing any more detail about your project it's a tricky question to answer, but I'll give it a go.

All applications should start off simple, if you believe (like I do) that you should start by building the simplest thing that could possibly work. Given this, since you're using Rails, then in all likelihood the simplest thing would be to structure your app as a vanilla Rails 3 application. This will probably (I say 'probably' because I don't know any specifics about the app) allow you to get a beta version of your app up and running pretty quickly without worrying about complexities which at this stage in the development of your project are not a problem.

If you need to create an XML or JSON-based API then Rails makes this really easy using the standard framework, which will allow you to spend more time thinking about the API design than how to code it, and it's the API design which is the most important thing to get right in the first instance.

Similarly, your Admin site can be part of the same app just in a different namespace. If you find later down the line that you want it as a separate app, you can do this (maybe you could use the awesome API you designed to facilitate this), but why bother designing it with this added complexity (and hence extended development time) in the first place if you don't have a good reason for doing so?

Once you have your app up and running and people are starting to use it, you start to get a picture of where the bottlenecks are and where the design could be improved. At this stage, if there's a need, you can start to move parts of the app to scalable solutions, such as running your API as a standalone service, introducing caching, changing data stores and other improvements and optimisations.

Even if your app is as wildly successful (and I hope it is!) then re-architecting your application whist continuing to run the existing service is still entirely possible, as Twitter have proved. Just stick to Knuth's statement and you'll be alright.

Regarding reading material, that's a tricky one. For me a lot of the XP and agile development classics taught me a huge amount about how to approach program and app design. I'd also check this StackOverflow topic for book inspiration.

Good luck!

Storing user-generated text in database securely (Ruby/Rails)

8 votes

I'm trying to figure out a way to store user-generated text securely in a database (so that only the user is the one who can access his/her stored text). I could have Rails encrypt and decrypt the user's text entries using the user's password as the key, but if the user ever forgot their password there would be no way to ever decrypt their previous content/text (since the Rails app uses BCrypt to store only a hash of the password).

Does anyone know how that could be done? It looks like Dropbox does something like it: "All files stored on Dropbox servers are encrypted (AES-256) and are inaccessible without your account password." (http://www.dropbox.com/help/27) Yet they allow you to reset your password and I'm assuming they don't store your plain text password anywhere.

What am I missing? Any suggestions would be greatly appreciated. Thanks!

Build on Gintautas' Option 1 with a two-prong encryption plan:

  1. Apply option 1, with a key that is known to the server, and
  2. Store the database on disk in an encrypted format with a key that is known only to the server. E.g., in an encrypted volume. When the server starts up, the key must be manually entered in order to access the database.

This "static security" provided by part 2 protects against an intruder in the system gaining access to the database files. Maybe not 100% the exact security you're after, but getting closer.

Can't install pg gem on Windows

6 votes

I've got 2 Ruby versions: 1.8.7 and 1.9.2 and PostgreSQL 8.3. I cant install pg gem on any of them. Getting this error:

C:/Development/Ruby187/bin/ruby.exe extconf.rb
checking for pg_config... yes
not recorded
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
 --with-opt-dir
 --without-opt-dir
 --with-opt-include
 --without-opt-include=${opt-dir}/include
 --with-opt-lib
 --without-opt-lib=${opt-dir}/lib
 --with-make-prog
 --without-make-prog
 --srcdir=.
 --curdir
 --ruby=C:/Development/Ruby187/bin/ruby
 --with-pg
 --without-pg
 --with-pg-config
 --without-pg-config
 --with-pg-dir
 --without-pg-dir
 --with-pg-include
 --without-pg-include=${pg-dir}/include
 --with-pg-lib
 --without-pg-lib=${pg-dir}/lib

I know it's a common problem, but I haven't found any working solution yet... Oh, I have added C:\Program Files (x86)\PostgreSQL\8.3\bin to my PATH.

Hello,

The message you're getting is a clear indication that you lack something for the correct installation of that gem:

Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options.

There is no Windows native version of latest release of pg (0.10.0) released yesterday, but if you install 0.9.0 it should install binaries without issues.

Anyhow, if you want to install the gem, you need a build environment installed. If you're using RubyInstaller, then you need the DevKit

Installation of the gem will only require you provide additional options to gem installation (like --with-pg-dir)

subst X: "C:\Program Files (x86)\PostgreSQL\8.3"
gem install pg -- --with-pg-dir=X:
subst X: /D

How to change a Ruby on Rails application name ?

6 votes

I have a Ruby on Rails application that was created using:

rails new old_name -d mysql

Now I want to change the application name to be new_name.

Just changing the application folder name will not be enough, because the database name, for example, also has to be changed (from old_name_development to new_name_development). I wonder if there are other places in the automatically generated files that needs changing.

Is there any built in command for changing the application name ?

in Rails 3, the application class is defined in config/application.rb, and referred to in your environment files (config/environment.rb, config/environments/*.rb) and config/routes.rb. I think that's it, but you should find out pretty quickly from rails server if you missed one. :)

That said, unless you've got a very specific reason for wanting it changed, I wouldn't bother. Doesn't really affect the application in any other way.

What is this Ruby function doing?

6 votes

I am confused on how this returns:

def utc2user(t)
  ENV["TZ"] = current_user.time_zone_name 
  res = t.getlocal 
  ENV["TZ"] = "UTC"
  res
end

It first sets the ENV variable, then sets 'res' to the local value, then re-assignes ENV variable, then returns res?

Not sure I understand how this is convering from UTC to the user time zone?

The first line is setting the environmental time zone variable to the user's time zone in order to get the res value in the correct time for that user. If it didn't set it to the user's, the time would still be in UTC.

It then sets the environmental variable back to UTC time, which I assume is the application's default.

It then returns res.

Rails & Devise: How to render login page without a layout?

6 votes

I know this is probably a simple question, but I'm still trying to figure Devise out...

I want to render :layout => false on my login page; how can I do this with Devise?

You can subclass the controller and configure the router to use that:

class SessionsController < Devise::SessionsController
  layout false
end

And in config/routes.rb:

devise_for :users, :controllers => { :sessions => "sessions" }

You need to move the session views to this controller too.

OR make a method in app/controllers/application_controller.rb:

class ApplicationController < ActionController::Base

  layout :layout

  private

  def layout
    # only turn it off for login pages:
    is_a?(Devise::SessionsController) ? false : "application"
    # or turn layout off for every devise controller:
    devise_controller? && "application"
  end

end

Rails 3/Cucumber problem: "...already activated builder 3.0.0, but your Gemfile requires builder 2.1.2"

6 votes

Hi Folks,

I've been using cucumber without trouble for with Rails 3 for a while, but after a whole bunch of tinkering today (including gem cleanup), I get the following error whenever I run "cucumber features"

You have already activated builder 3.0.0, but your Gemfile requires builder 2.1.2. Consider using bundle exec. (Gem::LoadError)

Tried it in multiple rails projects on my machine - all are effected. Not quite sure how to tackle this one - tried installing 2.1.2 & specifying it in the gemfile, but no joy.

"bundle exec cucumber features" does work, but it doesn't seem to play nicely with autotest.

Any suggestions regarding what I've done (and better still how to fix it) much appreciated.

It looks like after your gem cleanup, builder has been removed and then installed latest version (3.0.0). But rails3 and some of other gems requires ~> 2.1.2, which means that builder version should be >= 2.1.2 and < 3.0.0. So you need to remove 3.0.0 from your system gems:

gem uninstall builder

Use sudo if needed.

Then in your project:

bundle install

NOTE: If you had put manually builder into your Gemfile, make sure that you put ~> 2.1.2. Otherwise bundler will try to install latest stable version (3.0.0), which is not compatible with current version of rails and other popular gems:

gem "builder", "~> 2.1.2"

I would recommend you to store gems in separate locations for each project:

bundle install --path .gems

In this case you can do everything you want with your system gems and it will reduce risk to get in situation like you do now.

removing "utf8=✓" from rails 3 form submissions

6 votes

I have a simple search form in my Rails 3 app:

<%= form_tag search_path, :method => "get" do %>
  <%= text_field_tag :q, params[:q] %>
  <%= submit_tag "search", :name => nil %>
<% end %>

When the user hits the submit button, they get taken to the URL http://myapp.com/search?utf8=%E2%9C%93&q=foobar (where %E2%9C%93 gets displayed as a checkmark).

I'm not doing anything with the utf8 parameter, so I want to keep the URL clean by removing it entirely. That is, I want users to get taken to the URL http://myapp.com/search?q=foobar instead.

How do I do this?

Even though you aren't doing anything with the parameter, Rails is. It's to correct some issues in IE's parameter encoding. Yehuda has more info here:

What is the _snowman param in Rails 3 forms for?