Add something new to Virb:

Virb

Are you sure you want to delete that?

or Cancel

 

About

I devise and implement compelling and intellectual ideas into TriLab Media projects through methodical structures and experimentation.

TriLab Media, LLC

Groups(3)

The Ruby On Rails GroupThe RAE Magazine Online GroupThe Muse Group

Following(10)

Stephen's PictureLuumu's PictureThe Chemist's PictureRAE Magazine Online's PictureSleepwalker Dining (Needs Vocalist!)'s Picture72photos's Picture

NovemberNov 22 Sunday Sun 09

Win a new Canon 7D (or 2500 photo scans) from @ScanCafe & Scott Bourne. Pls RT. Details here: http://bit.ly/dgYgA

updated 1 week ago via Twitter

NovemberNov 6 Friday Fri 09

Follow Friday @raemag | Guitar Instruction. Finely Tuned.

updated Nov 6, 2009 via Twitter

SeptemberSep 4 Friday Fri 09

I've just come to the realization that my iPhone's sole purpose has been being a super-advanced alarm clock. #technologyutilizationfail

updated Sep 4, 2009 via Twitter

SeptemberSep 1 Tuesday Tue 09

Nominating this photo for the @Virb Photo Sweepstakes: http://virb.com/p/2301312 #virb

updated Sep 1, 2009 via Twitter

AugustAug 31 Monday Mon 09

8 Tips To Supercharge Your Rails App

Ruby on Rails is a elegant framework with an abundance of built in functions. However, sometimes finding and implementing the right ones for your project isn't always easy. Here, we'll review 8 lesser-known tips that will enable you to get the most out of your dynamic web application.


alt

1. Dynamic Blocks of Code

There may be times when you'd like to include a certain javascript or css file on certain pages, but not the entire site. This is a perfect example to utilize the content_for function.

On the page or pages you'd like to include the specific javascript or CSS files. Put this block of code at the top of that template.


  
  

Next, open your global layout and insert this right before the tag.

2. Load Models From Sub-Directories

It's no fun sifting through dozens of models in order to find the one you're looking for. A great way to organize your models is to place them in sub-directories of the models folder and have your application load them from there.

In your config/environment.rb file. Add this line of code within the Rails::Initializer.run do |config| section.

Dir.glob("#{RAILS_ROOT}/app/models/*[^(.rb|.ignore)]").each{|dir| config.load_paths << dir }

Don't forget to restart your app after any config changes such as this.

3. Make Your Own YML Configuration File

Using a YML config file can enable you to keep all your application's global variables in one place and have the ability to call them from anywhere.

To get started, let's create our config file, config.yml in the config directory and add a few variables to it. You may add as many variables as you'd like.

development:
  app_name: MyApp
  support_email: support@mydomain.com

test:
  app_name: MyApp
  support_email: support@mydomain.com 

production:
  app_name: MyApp
  support_email: support@mydomain.com

Next, we'll need to load this configuration into our application by adding a line to the config/initializers/configs.rb file.

MY_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/config.yml")[RAILS_ENV]

Now you can call any of the variables set in config.yml by using the following.

MY_CONFIG["app_name"]

4. Parse An RSS feed in seconds

Parsing RSS feeds in rails is extremely simple, however, you may come across complicated solutions for accomplishing it. Here's a super fast way to parse any RSS feed and display it's contents in your view.

In your controller, on the first line (above everything) add:

require 'rss'

Then, add an action (or add to an existing action):

def index
  @rss = RSS::Parser.parse(open('http://weblog.xmgnetworks.com/?feed=rss2').read, false)
  @entries = @rss.items[0..4] # Limited to 5 items, remove or change as needed
end

And finally in your view, add a variation of this (customize based on the data provided in the feed).


  
  

5. Use Serialized Hashes

In some cases you may want to store multiple pieces of data and associate it with a model. For instance, if you have a users table and would like have the ability to store preferences for each user. One way this could be done would be to create a table called user_preferences and link them with a basic Rails association. But, a much simpler way to do this without the need to create more tables or files, is by using the "serialize" function provided by Rails.

To get started, we'll first need to add a column to our existing users table called preferences, you can do this with a simple rails migration.

script/generate migration add_preferences_to_users
add_column :users, :preferences, :text

Then, we'll need to add a serialize function to our users model, near the top in order to activate serialization for the preferences column.

serialize :preferences

That's all! To add preferences for a user you can use the following function.

@user.update_attributes(:preferences => { "hide_age" => "true" })

6. Use Helpers with Blocks of Code

Helpers are an integral part of rails, but using them strictly inline can limit their potential. Here's how you can pass a block of code from your views into a helper method.

In this example, we'll be generating boxes for a sidebar on the fly. This way, instead of repeating all the styling of our box each time we use one in our views, we'll just need to add the content for them.

Let's start with the view. In the template where we'd like our box, add the following snippet of code. Repeat this snippet for multiple boxes.


	Content for my box.

The line "sidebar_box("my_box_id") do" will call a helper function called "sidebar_box" and pass a variable to it called "My Box Title" that we'll use for the title of our box.

Next, we add our helper function by opening application_helper.rb and adding the following function.

def sidebar_box(title, &block)
 data = capture(&block)
 content = 
    ''
 concat(content)
end

The first line in this function, data = capture(&block), will capture everything contained within the sidebar_box block in your view. Next, in the content = line, we add the hardcoded HTML each box will have and the dynamic content we captured from the block in our view, here you can freely add any HTML you wish.

Lastly, we use the concat(content) function to bind everything together and send it back to your view.

7. Loading dynamic stylesheets

Splitting your stylesheet into several smaller stylesheets is a great organizational practice, especially if you find your stylesheet growing over the 1000-line mark. In rails, a great naming convention for your stylesheets is to name them after each of your controller's and then load them into your pages dynamically.

A simple way to do this, is to open your application.rb controller and add the following snippets of code.

First, we'll add a method to find stylesheets to load into your pages depending on what controller the user is on. If no stylesheet for the controller is found, it simply does nothing.

def find_stylesheets
  @stylesheets = [] # A new empty array
  stylesheets_path = "#{RAILS_ROOT}/public/stylesheets/" # The path to our stlesheets folder

  candidates = [ "#{controller_name}" ] # Use the controller name for the stylesheet to search for
  
  candidates.inject("") do |buf, css| 
    if FileTest.exist?("#{stylesheets_path}/#{css}.css") # Search for a matching stylsheet
      @stylesheets << css # Add it to our array
    else
      @stylehseets = [] # If no matches, add nothing to our array
    end
  end
end

Next, add a before_filter near the top of your application controller to call this method before each page load.

before_filter :find_stylesheets

Lastly, we'll add a styleshet_link_tag into the section of our global layout template that will be populated with the stylesheets found in the above method.

8. Quickly Aggregate and Display Data from Multiple Model's

Displaying information from multiple models, that each have different field names can be a challenge. But Rails makes it easy to do this in a few simple steps.

A common example would be creating an activity stream for your users that displays their activity throughout your application.

First, we'll need to construct a controller method to fetch all of the information we want to display. Here's an example.

def activity_stream
  blog_posts = BlogPost.find(:all, :conditions => ["user_id = ?", @user.id])
  comments = Comment.find(:all, :conditions => ["user_id = ?", @user.id])
  # Add any models you wish to add to the stream
  @activity_stream = blog_posts + photos
end

Next, we'll add the activity to our view and call a helper method to sort through each type of activity.


	

Lastly, we add our helper method that will allow you to customize what information appears for each type of activity item. This can be customized with HTML styling and any other fields from your model that you'd like to display.

def activity_item_for(item)
  case item.class.name
  when 'BlogPost'
    "#{item.title}"
  when 'Comment'
   "#{item.body]"
  end
end

(via From Two 2 Twelve - general)

AugustAug 24 Monday Mon 09

Battling against color profiles and missing thumbs on the eve of the @raemag beta launch.

updated Aug 24, 2009 via Twitter

AugustAug 22 Saturday Sat 09

Win a new Canon 5DMKII (or $2500 Gift Cert) from @OPGear & Scott Bourne. Details here: http://bit.ly/BqU8N

updated Aug 22, 2009 via Twitter

AugustAug 14 Friday Fri 09

It's about time... http://bit.ly/3y2Zyl

updated Aug 14, 2009 via Twitter

AugustAug 11 Tuesday Tue 09

RT @raemag Article submissions now open! Interested in writing for raemag.com? We're offering $15/article. Details at http://bit.ly/BQxGQ

updated Aug 11, 2009 via Twitter

Quickly finding that some things should never be in a tree structure...Task lists being the first among them.

updated Aug 11, 2009 via Twitter

Older →

Flag this profile!

Flag this profile as:

or Cancel