Thursday, April 21, 2011

Add Rails Support to Netbeans 7.0

I always liked Netbeans for coding: it supports ton of languages, can be installed in Windows, Linux and MaC, and is stable in all of them. Even it demands more resources than a text editor, this is not a problem in current computers.

The latest release (7.0) dropped official support for Rails :( .
However you can continue using it via a community maintained plug-in:
  •  Install Netbeans from http://netbeans.org/downloads/index.html (I picked PHP distribution since it is the lighter one)
  • Add a plugin repository : 
    • Tools -> Plugins -> Settings 
    • click 'Add' and write a name (e.g: Beta rails) and a url 'http://updates.netbeans.org/netbeans/updates/7.0/uc/beta/stable/catalog.xml.gz'
  • refresh available plugins, filter by 'rails' and install it
  • Restart IDE, rescan Ruby platforms:
    • Tools -> Ruby Platforms --> Autodetect Platforms
 
Profit

 here are some links for more information on NB + Rails:
  • http://blog.enebo.com/
  • http://wiki.netbeans.org/RubyCommunityInformation 

Wednesday, April 13, 2011

Rendering from a Model in Rails 3

Call me 'rebel', but it happened to me that I had to render text from a ruby class.
I was composing text withing a regular class to send personalized SMS's and I wanted to use 'erb' templates and some other view utilities. Even it is not the Rails way, I wanted to do so.

Here are the tricks I used to build the logic. Key points are:
- how to get access to the view context
- how to get access to the path and the erb templates
- hot to get access to the url helpers in case you need form an url


class MyModel < ActiveRecord::Base
 
   # Use the my_models/_my_model.txt.erb view to render this object as a string
  def to_s
    url = helpers.new_user_url :host => default_host
    view = ActionView::Base.new(views_path)
    text = view.render(
      :partial => 'my_models/my_model', :format => :txt,
      :locals => { :my_model => self, :url => url}
    )
  end
 
  private
  def views_path
    @views_path ||= Rails.configuration.paths.app.views.first
  end

  def self.helpers
    @helpers ||= Rails.application.routes.url_helpers
  end

  def default_host
    #you need to configure it in your /config/environments/*.rb files
    # for example:   config.action_mailer.default_url_options = { :host => 'localhost:3000' }
    @default_host ||= Rails.configuration.action_mailer.default_url_options[:host]
  end
 
 
end