Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 463 total  RSS 

List HTTP Status Codes in Rails

If you follow the Rails way of RESTful controllers you should familiarize yourself with all the return status codes available in the HTTP protocol.

The following is a handy list, like "rake routes", for listing out all the HTTP codes that you can return in your controller logic.

   1  
   2  desc 'Lists ActionController::StatusCodes::STATUS_CODES like routes'
   3  task :status_codes => :environment do
   4    puts "Status - Name"
   5    ActionController::StatusCodes::STATUS_CODES.to_a.sort.each { |code, message| 
   6      puts "#{code}    - #{message.gsub(/ /, "").underscore.to_sym}"
   7    } if ActionController::StatusCodes.constants.include?('STATUS_CODES')
   8  end

Setting user locale in Globalize, the working solution

This example application, provided as Globalize's, documentation doesn't work at all.

This is what worked for me:

   1  
   2      before_filter :set_locale
   3  
   4      def set_locale
   5        request_language = request.env['HTTP_ACCEPT_LANGUAGE']
   6        request_language = request_language.nil? ? nil : request_language[/[^,;]+/].split('-')[0]
   7  
   8        @locale = params[:locale] || request_language || Locale.base_language.code
   9  
  10        if !params[:locale].nil? && LOCALES.keys.include?(params[:locale].to_sym)
  11          Locale.set LOCALES[@locale.to_sym]
  12        else
  13          redirect_to params.merge('locale' => @locale)
  14        end
  15      end

Quick-Start Rails Server Wherever You Are

Set a workspace directory, and you can use this script to quickly launch any Rails application on port 80 by only typing the first few letters, wherever you are.

Eg. "rlaunch r" will find a project in your workspace directory that starts with "r", in this case "rails_is_awesome".

   1  
   2  ~$ rlaunch r
   3  Loading rails_is_awesome...
   4  ** Starting Mongrel listening at 0.0.0.0:80
   5  ** Starting Rails with development environment...
   6  ** Rails loaded.


If you have more than one that starts with r, it'll show you all available projects that start with that pattern.

   1  
   2  ~$ rlaunch r
   3  rails_is_awesome
   4  rad_site 


Save as rlaunch, then "chmod u+x rlaunch" and put it somewhere in your path.

   1  
   2  #!/usr/bin/env ruby
   3  require 'abbrev'
   4  
   5  WORKSPACE = "/Users/#{ENV['USER']}/Workspace"
   6  
   7  begin
   8    entries = []
   9    Dir.entries(WORKSPACE).each do |f|
  10      entries << f if File.directory?("#{WORKSPACE}/#{f}")
  11    end
  12    entries.slice!(0, 2)
  13    entries= entries.abbrev
  14    if entries[ARGV[0]].nil?
  15      alternatives = []
  16      entries.each do |k, v|
  17        alternatives << v if k =~ /^#{ARGV[0]}/
  18      end
  19      alternatives.uniq!
  20      puts alternatives.empty? ? "No projects start with #{ARGV[0]}." : alternatives
  21      exit
  22    end
  23    puts "Loading #{entries[ARGV[0]]}..."
  24    Dir.chdir("#{WORKSPACE}/#{entries[ARGV[0]]}")
  25    `sudo script/server -p 80`
  26  rescue
  27    puts "An error occurred."
  28  end

ruby - merb edge + feather install

   1  
   2  ..install merb / etc / feather
   3  
   4  ..install dependencies
   5  sudo gem install addressable english rspec
   6  sudo gem install archive-tar-minitar tzinfo
   7  
   8  ..install merb edge
   9  git clone git://github.com/sam/extlib.git
  10  cd extlib
  11  sudo rake install
  12  cd ..
  13  
  14  sudo git clone git://github.com/wycats/merb-core.git
  15  sudo git clone git://github.com/wycats/merb-more.git
  16  sudo gem install erubis rake json_pure rspec rack hpricot mime-types
  17  cd merb-core ; sudo rake install ; cd ..
  18  cd merb-more ; sudo rake install ; cd ..
  19  
  20  ..install datamapper-edge
  21  
  22  ..make sure you have openssl-ruby installed otherwise these will not compile!
  23  
  24  sudo aptitude install openssl-ruby
  25  
  26  
  27  sudo gem install ParseTree -v=2.1.1
  28  sudo gem install ruby2ruby -v=1.1.8
  29  sudo gem install addressable english rspec
  30  mkdir -p ~/src cd ~/src
  31  sudo gem install sake
  32  sake -i http://github.com/dkubb/dm-dev/tree/master/dm-dev.sake?raw=true
  33  sake dm:clone
  34  cd dm
  35  sake dm:install
  36  
  37  ..download feather
  38  git clone git://github.com/fujin/feather.git
  39  git clone git://github.com/fujin/feather-plugins.git
  40  cd feather
  41  
  42  ..create database.yml in /feather/config/database.yml
  43  development:
  44      adapter: mysql
  45      database: feather
  46      username: root
  47      password:
  48      host: localhost
  49  #   socket: /var/run/mysqld/mysqld.sock
  50  
  51  ..save file then
  52  cd ..
  53  mkdir db
  54  
  55  ..create database manually
  56  mysql -u root [password]
  57  
  58  ..then create db
  59  create database feather;
  60  
  61  ..then exit mysql
  62  exit;
  63  
  64  ..now init the feather database
  65  merb -i
  66  
  67  ..then in the merb console (specific to merb-edge)
  68  Database::initial_setup
  69  DataMapper.auto_migrate!
  70  
  71  ..exit merb console, then run
  72  merb
  73  
  74  ..navigate browser to
  75  http://localhost:4000/         [your blog]
  76  http://localhost:4000/admin    [admin panel]
  77  
  78  ..your admin login will be initially
  79  username:admin
  80  password:password

debian etch - install ruby 1.8.6 + rubygems from source + add tools

// debian etch - install ruby 1.8.6 + rubygems from source

   1  
   2  //build essentials
   3  sudo aptitude install ssh gcc sudo build-essential make git-core subversion -y
   4  sudo aptitude install bash man-db cron wget lynx bind9 -y
   5  sudo aptitude install mysql-server mysql-client libmysqlclient15-dev libmysql-ruby sqlite3 imagemagick -y
   6  
   7  //now ruby 1.8.6 from source
   8  cd /usr/src
   9  wget ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.6-p114.tar.gz
  10  tar xfz ruby-1.8.6-p114.tar.gz
  11  cd ruby-1.8.6-p114
  12  ./configure --prefix=/usr/local
  13  sudo make 
  14  sudo make install
  15  
  16  //now gems from source
  17  cd /usr/src
  18  wget http://rubyforge.org/frs/download.php/38646/rubygems-1.2.0.tgz
  19  tar xfz rubygems-1.2.0.tgz
  20  cd rubygems-1.2.0
  21  sudo ruby setup.rb
  22  
  23  //update with
  24  sudo gem install rubygems-update
  25  sudo update_rubygems
  26  

Rails 2.1.0 monkey patch to add the recognized or matched rails route to the request

This was based on code I found here from Chris Cruft - http://cho.hapgoods.com/wordpress/?p=151

Enhanced to support rails 2.1.0 and also allows alias method chains for recognize from other plugins still to work.

   1  
   2  module ActionController
   3    class AbstractRequest
   4      attr_reader :recognized_route
   5      
   6      def init_recognized_route_from_path_parameters
   7        recognized_route = path_parameters.delete(:recognized_route) 
   8      end
   9    end
  10  
  11    module Routing
  12      
  13      class RouteSet
  14        def recognize_with_route(request)
  15          result = recognize_without_route(request)
  16          request.init_recognized_route_from_path_parameters
  17          result
  18        end
  19        alias_method_chain :recognize, :route
  20  
  21        def write_recognize_optimized_with_route
  22          tree = segment_tree(routes)
  23          body = generate_code(tree)
  24          instance_eval %{
  25            def recognize_optimized(path, env)
  26              segments = to_plain_segments(path)
  27              index = #{body}
  28              return nil unless index
  29              while index < routes.size
  30                result = routes[index].recognize(path, env) and result[:recognized_route] = routes[index] and return result
  31                index += 1
  32              end
  33              nil
  34            end
  35          }, __FILE__, __LINE__
  36        end
  37        alias_method_chain :write_recognize_optimized, :route
  38  
  39      end
  40    end
  41  end
  42  

Sharing has_many extensions

Sometimes you extend an ActiveRecord association this way:

   1  
   2  has_many :things do
   3    def active
   4      find :all, :conditions => ['active = ?', true]
   5    end
   6  end


You can share the same extensions using a lambda:

   1  
   2  
   3  extensions = lambda {
   4    def active
   5      find :all, :conditions => ['active = ?', true]
   6    end
   7  }
   8  
   9  has_many :things, &extensions
  10  has_many :more_things, &extensions
  11  

Automatic Expiration of Rails Action Caching

Would love to get some feedback on this...

No doubt, 5 minutes after posting this, someone will tell me of the built-in Rails way of doing this, but alas I could not find it.

Usage looks like this:

   1  
   2  class PeopleController < ApplicationController
   3    caches_action :show, :for => 1.hour, :cache_path => Proc.new { |c| "people/#{c.params[:id]}_for_#{Person.logged_in.id}" }
   4  end


The ":for => 1.hour" part is where the magic happens.

Basically, this bit of code adds a before_filter that checks the last modified time of the cache entry, and expires it if it is older than the specified time period.

   1  
   2  module ActionController
   3    module Caching
   4      module Fragments
   5        # expire a cache key only if the block returns true or
   6        # if the age of the fragment is more than the specified age argument.
   7        def expire_fragment_by_mtime(key, age=nil, &block)
   8          block = Proc.new { |m| m < age.ago } unless block_given?
   9          if (m = cache_store.mtime(fragment_cache_key(key))) and block.call(m)
  10            expire_fragment(key)
  11          end
  12        end
  13      end
  14      module Actions
  15        module ClassMethods
  16          # adds an option :for
  17          # caches_action :show, :for => 2.hours, :cache_path => ...
  18          # :cache_path is required, unfortunately
  19          def caches_action_with_for(*actions)
  20            original_actions = actions.clone
  21            options = actions.extract_options!
  22            if for_time = options.delete(:for)
  23              cache_path = options[:cache_path]
  24              before_filter do |controller|
  25                cache_path = cache_path.call(controller) if cache_path.respond_to?(:call)
  26                controller.expire_fragment_by_mtime(cache_path, for_time)
  27              end
  28            end
  29            caches_action_without_for(*original_actions)
  30          end
  31          alias_method_chain :caches_action, :for
  32        end
  33      end
  34    end
  35  end
  36  
  37  # Add a method to grab the last modified time of the cache key.
  38  # If you use a store other than the FileStore, you'll need to add
  39  # a method like this to your store.
  40  module ActiveSupport
  41    module Cache
  42      class FileStore
  43        def mtime(name)
  44          File.mtime(real_file_path(name)) rescue nil
  45        end
  46      end
  47    end
  48  end

Radiant freeze gems

   1  
   2  rake radiant:freeze:gems

Rails ajax star rater

Here's some Rails code I created to try out the CSS Star Rating Redux from Komodo Media.

I set up my routes.rb to use REST.

   1  map.resources :titles, :member => { :rate => :any }


I use the Ruby Linguistics Framework to make this implementation easier. Install it using RubyGems (sudo gem install linguistics). And then put the following code at the top of your application_helper.rb file.

   1  require 'linguistics'
   2  Linguistics::use(:en)  # extends Array, String, and Numeric


This code goes in the page you want the rater to appear in, in this example, show.html.erb.

   1  <ul class="star-rating" id="<%= dom_id(@title) -%>_rating"><%= render :partial => '/partials/star_rating', :locals => { :record => @title } %></ul>


Create a partial called _star_rating.html.erb in your RAILS_ROOT/views/partials directory.

   1  <li class="current-rating" style="width: <%= number_to_percentage((record.rating.to_f * 25) / (5 * 25) * 100) -%>;">Currently <%= record.rating -%>/5 Stars.</li>
   2  <% (1..5).each do |i| -%>
   3      <li><%= link_to_remote pluralize(i, 'Star'), {
   4          :update => "#{dom_id(record)}_rating",
   5          :url => eval("rate_#{record.class.name.downcase}_url(:rating => #{i})")
   6      }, {
   7          :class => "#{i.en.numwords}-#{i.abs == 1 ? 'star' : 'stars'}",
   8          :title => "#{pluralize(i, 'star')} out of 5"
   9      } -%></li>
  10  <% end -%>
« Newer Snippets
Older Snippets »
Showing 1-10 of 463 total  RSS