RailsCasts Pro episodes are now free!

Learn more or hide this

Recent Comments

Avatar

Just a heads up, you don't need to do this:

coffeescript
@Product = Product

For the Product class to be globally available. You can combine that into the actual definition of the class, like such:

coffeescript
class @Product
  # etc...
Avatar

Worth noting that you can use bundle install --binstubs --shebang ruby-local-exec instead of replacing with sed.

I can't find documentation for the --shebang flag anywhere, but it has the desired effect.

Excellent episode, looking forward to chef/capistrano in the future!

Edit: The --shebang option is defined here in the source.

Avatar

what's the benefit to using therubyracer (V8) vs therubyrhino (mozilla)?

therubyracer is api compatible with therubyrhino but doesn't require python to be installed to compile.

Avatar

I concur.

I find this to be a pretty nice proof of concept, but I'd rather skip JavaScript validation entirely than going down this route.

Avatar

Re: memory leaks, it seems like it would be easy to attach a counter to the JS context and say, every 1000 uses, go ahead and dump the existing context and re-build a new one. Inelegant, but effective! Just wanted to throw that idea out there.

Avatar

I think this a bit of a stretch... while there might be some situations when this kind of mojo would be helpful I don't it should be normal practice. In fact it breaks the MVC somewhat. What I normally do is one of two things: either app is fully JS–based and logic is processed via JS while rails acts as server side model or use ajax to fetch pre–processed data and only display them via js code.

Avatar

Great screencast.

It would be cool if we could use helpers from Rails (number_to_currency etc.) in JS :( bu t that is not possible.

Avatar

It's actually slower (Sizzle uses document.getElementById when you do $('#..'), actually). Your solution is a good idea when you have multiple links, but just having one makes the id a better approach.

Very nice episode !

Avatar

Nice editor, but what about rendering a flash if the editing doens't pass the validation?

Avatar

Thanks for the cast! Looks great. Is it possible to edit the source html directly? That would be a must have for me to use Mercury Editor.

Avatar

Awesome episode as always, thanks!

One question, though: Do you need to add an id to the edit link?

I usually filter by the data attribute. I mean, instead of this:

javascript
  var link = $('#mercury_iframe').contents().find('#edit_link');

I usually do something like this:

javascript
  var links = $('#mercury_iframe').contents().find('a:data(save-url)');

Am I missing some obvious drawback by using this approach?

Avatar

Thanks for catching that, I've corrected it :)

Avatar

Hello! Thank you for lesson. Can you help me? I have error after db:migrate

rake db:migrate
rake aborted!
undefined method `devise' for User(Table doesn't exist):Class

Tasks: TOP => db:migrate => environment
(See full trace by running task with --trace)

Avatar

In this case, I think Ryan just suggested you would use a Prawn::Document object inside your OrderPdf class, instead of inheriting from it. So for example, you would change:

ruby
class OrderPdf < Prawn::Document
  def initialize
    super
    text "Order goes here"
  end
end

into:

ruby
class OrderPdf
  def initialize
    @pdf = Prawn::Document.new
    @pdf.text "Order goes here"
  end

  def render
    @pdf.render
  end
end

(or use the delegate method mentionned by syath instead of writing your own render method)

In general, prefer composition to inheritance is considered good engineering practice because you control more tightly what your class exposes when you "use" an object rather than inheriting from it, so you have less surprises in the future.

For example, if a new version of Prawn renames the render function to render_document, you can just modify your own render method to use the new render_document one, instead of having to track every usage of render in your application. Or if you want to scrap Prawn and use another library, you can probably just modify your OrderPdf without rewriting a single line outside of it.

That's what we mean when we say that composition offer better encapsulation than inheritance.

Avatar

Tried it with Rails 3.1.1.rc3 but got
uninitialized constant Uhoh (NameError) when trying
to mount the engine from another rails application.

Then I thought perhaps I have to do build/install the plugin
as a gem. After doing this and including the gem uhoh in the
main app's Gemfile the problem went away.
Not sure if this is correct.

Avatar

Hey guys!

I am using JQuery Mobile for markup, and I notice that link_to_add_fields in application_helper.rb doesn't convert the rendering to jquery mobile style. It makes sense, JQuery Mobile would mark up the things with its framework before rendering it to the browser. However, is there a way to get around this problem and render it on server side?

Avatar

Thanks. If you use .try(:admin) instead, the redirect works correctly even if you aren't logged in:

ruby
require 'resque/server'

class Resque::SecureResqueServer < Resque::Server
  before do
    redirect '/' unless request.env['warden'].user.try(:admin)
  end
end

That also uses the Resque:: namespace and is loaded by Rails automatically if you use it in e.g. app/initializers/resque_auth.rb.

In your routes.rb, you would include:

ruby
mount Resque::SecureResqueServer, :at => "/resque"
Avatar

Thanks for the great episode, but erg... I'm a little frustrated with the RailsCasts site.

I wrote a comment then cmd + clicked "Show Notes" to try to reference something in the show notes thinking it would pop open that page in a new browser window. Unfortunately, it didn't. When I tried to click back to get back to this page, I had lost my written-but-not-submitted comment. Can you either 1) make it so you can cmd + click "Show Notes" and open a new browser window with the show notes page or 2) make is so you can click back to return to this form without loosing the form data?

Here is my comment again, though I'm going to paraphrase this time:

I believe you can use Factory instead of FactoryGirl in factories.rb and your spec files. For example:

ruby
FactoryGirl.define :user { |f| f.name "Matt" }
Factory.create :user { |f| f.name "Matt" }

FactoryGirl.create(:user)
Factory.create(:user)

I prefer not to include Factory::Syntax::Methods in my spec_helper.rb, as I like to explicitly show that I'm using a factory to build/create objects. Just using create or build might be misinterpreted as ActiveRecord calls.

Avatar

Great cast!

I just wish there was a cast with more basic stuff about rspec, from installation, to running, possible errors, how do make fixtures work, etc...

Thank you

Avatar

For trouble on windows

On my windows 7 box I had to do

shell
$ bundle exec guard

could not use

shell
$ guard
Avatar

You can also create a default one for any field. This will search for any value in any column.

Any Clause
when "allfields"
                                where('firstname LIKE ? OR lastname LIKE ? OR email LIKE ? OR manager LIKE ? OR address1 LIKE ?  OR address2 LIKE ?  OR city LIKE ?  OR state LIKE ?  OR zipcode LIKE ? ', "%#{search}%","%#{search}%", "%#{search}%","%#{search}%", "%#{search}%","%#{search}%", "%#{search}%","%#{search}%", "%#{search}%")                        
Avatar

Instead of just using name to search on, you can modify your model to include the field you wish to search on.

model
        def self.search(search,type)
          if search
            case type
                        when "firstname"
                                where('firstname LIKE ?', "%#{search}%")
                        when "lastname"                                
                                where('lastname LIKE ?', "%#{search}%")
                        when "email"
                                where('email LIKE ?', "%#{search}%")
                end
          else
            scoped
          end        
        end
Controller
USER.search(params[:search],params[:fieldtype])
index.html.erb
<%= select_tag "fieldtype", options_for_select([ "firstname", "lastname", "email" ], "firstname") %>
Avatar

I use Devise and have been trying to implement invitations. I am having an issues, can you help?

I can't get my devise model (user) to recognize the :invitation_token in the (new) method as pointed out in the episode, the hidden_field in the form never receives the invitation_token. It does get passed as a parameter though, I see it in logs.

Placing the :invitation_token and email assignments in the user_controller didn't work. I also created a registrations_controller and tried to override the new method. This didn't work either:

ruby
class RegistrationsController < Devise::RegistrationsController
  def new
    super
    @user = User.new(:invitation_token => params[:invitation_token])
    @user.email = @user.invitation.recipient_email if @user.invitation
  end
end

Here is my relevant routes.rb line:

ruby
devise_for :users, :controllers => {:registrations => 'registrations'} do
  get 'users/sign_up/:invitation_token' => 'devise/registrations#new', :as => "new_user_registration"
end

And invitation_controller.rb

ruby
Mailer.invitation(@invitation, new_user_registration_url+"/#{@invitation.token}").deliver

Any suggestions greatly appreciated, thank you.

Avatar

thanks for this, this is awesome, do you have any examples with it working? Not ready to play around w/ PJAX yet but i'd love to see what you did

Avatar

any idea if this works with mouseovers?

Avatar

I did exactly this. My public user models are made with sorcery. I then used activeadmin and devise to build the back office for me to use.

If you are ok with separate user and admin_user models this isn't a problem.

Avatar

I've actually forked off prawnto and merged all the fragmented branches into a gem. It's working well with Rails 3.1. I hope to continue development, so don't be shy about feature requests or contributions.

You can find it at https://github.com/forrest/prawnto

Avatar

Any tips on how to test the content of the pdf?

Avatar

I'm honestly not too familiar with the concept myself. After I watched the video I had the same curiosity. Found this: http://www.simonecarletti.com/blog/2009/12/inside-ruby-on-rails-delegate/

Hope it helps =]

Ryan: great screencast as always, I've been wanting to see an updated version of this one for a while :D

Avatar

Hi there, I am still rather new to programming. I at around 4:50 where Ryan says something about you can either have the orderpdf class inherit from prawn::document or something about delegating? I know it may be too long to explain here, but does anyone know of a good place to start looking? I don't know even what keyword to search on google about this..

Thank you!

Avatar

i could make spork relaod classes , but not when used with guard

Does somebody have a solution not to load theese damn models classes (reloading spork is so slow ...)

Avatar

i cannot see my model changes using cache_classe=false in test config, i had to add watch(%r{^app/models/.+.rb$}) into my guard file to reload spork but this is realy slow does anybody have an other solution ?

i use meta_where do you think it preloads classes ?

Avatar

Thanks Ryan, cast on cancellation would be great

Avatar

Thanks Ryan, cast on cancellation would be great

Avatar

Hi Ryan,
as always a very useful screencast! But here the hard question:

How do you test things like this?

Avatar

Twitter has a fork of mustache.js that at one time, at least, was much more robust than the original. I'm no sure if that's still the case. It's worth knowing about, though.

Avatar

That's how I was doing it prior to this episode, but it seems like window.pushstate isn't quite agreed upon between browsers on when the first time it should be fired (some browsers fire on page load, while others don't.)

Any tips with how you've dealt with this in order to make the back and forward buttons function properly (if we opt out of using pjax)?

Avatar

I put this in my application_helper.rb.
It does the trick quite nicely.

def current_user
  super.decorator
end
Avatar

I tend to store attributes like status or role as underscored strings (a string that would be
suitable for a method/variable name) sometimes a simple .humanize will do the trick when
it comes to displaying that value in the UI user but other times you need to customize
them a bit which is one reason I18n is great

Here's my ApplicationDecorator which helps automate the usage of I18n for
such a purpose.

https://gist.github.com/1338134

Avatar

So I am implementing this and I am slightly confused as the best way to access the presenter from the layout.

The reason I would like to do this is for menu building.

Has anyone else dealt with this?

Avatar

For the life of me, I cannot figure out how to get my guard logs in color. It's really hard to see without it. Tips anyone?

Avatar

When it comes to Autocomplete and Autosuggestion, what are people using?

Avatar

Ryan, are you hoping to add a cast on Braintree as well? Seeing that you use it and that they offer Ruby support, I'd love to see a cast on it. Is it similar to paypal in terms of setup on the Rails end? Thanks!

Avatar

I would be nice to see a Rails setup using Chef and/or Puppet.

Avatar

Please tag this episode with "async" and "asynchronous". It was really hard to dig back up, not remembering how the technology was applied or that the gem is called Faye.