Public
snipts » rails
showing 1-20 of 36 snipts for rails
-
∞ AppConfig
# For a application config (config/application.yml) # Request: AppConfig.variable_name # #-> config/initializers/AppConfig.rb module ApplicationConfiguration require 'ostruct' require 'yaml' if File.exists?( File.join(RAILS_ROOT, 'config', 'application.yml') ) file = File.join(RAILS_ROOT, 'config', 'application.yml') users_app_config = YAML.load_file file end default_app_config = YAML.load_file(File.join(RAILS_ROOT, 'config', 'application.yml')) config_hash = (users_app_config||{}).reverse_merge!(default_app_config) unless defined?(AppConfig) ::AppConfig = OpenStruct.new config_hash else orig_hash = AppConfig.marshal_dump merged_hash = config_hash.merge(orig_hash) AppConfig = OpenStruct.new merged_hash end end
-
∞ Installing mysql gem on snow leopard
$ sudo env ARCHFLAGS="-arch x86_64" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config $ sudo port install mysql5-devel $ sudo /opt/local/lib/mysql5/mysql_install_db -user=mysql $ sudo env ARCHFLAGS="-arch x86_64" gem install mysql -- --with-mysql-config=/opt/local/bin/mysql_config5
-
∞ To display error messages on localhost
# To display error messages on localhost # -> application_controller.rb def local_request? false end
-
∞ Ruby controller to supply data to Flot JS
def graph #Get last 8 weights, but after we build the Array for the JS Graph we need to reverse #the array so that it ends up chronologically. #Also counting down from the size of the weight list, b/c the graphing tool doesn't seem to # be tricked so easily @user = params[:id].blank? ? @current_user : User.find(params[:id]) @weight = Weight.find(:all, :conditions=>["user_id = ?", @user.id], :limit=>8 , :order=>'created_at DESC') @DataSet = Array.new @Ticks = Array.new counter = @weight.size for weight in @weight #counter = weight.created_at.strftime("%Y%m%d") counter = weight.created_at.to_i * 1000 @DataSet.push([counter,weight.weight]) @Ticks.push([counter,weight.created_at.strftime("%Y-%m-%d")]) end @DataSet.reverse! @Ticks.reverse! #Determine BMI ranges @bmi_ranges = {} @bmi_ranges["underweight"] = "from: 0, to:#{sprintf("%.2f",(18.5 * (@user.height_in_inches **2).to_f)/703) }" @bmi_ranges["normal"] = "from: #{sprintf("%.2f",(18.6 * (@user.height_in_inches **2).to_f)/703)}, to:#{sprintf("%.2f",(24.9 * (@user.height_in_inches **2).to_f)/703) }" @bmi_ranges["overweight"] = "from: #{sprintf("%.2f",(25 * (@user.height_in_inches **2).to_f)/703)}, to:#{sprintf("%.2f",(29.9 * (@user.height_in_inches **2).to_f)/703) }" @bmi_ranges["obese"] = "from: #{sprintf("%.2f",(30 * (@user.height_in_inches **2).to_f)/703)}, to: 2000" respond_to do |format| format.js end end
-
∞ date datetime picker jQuery UI for Rails
$(document).ready(function() { // Define the dateFormat for the datepicker $.datepicker._defaults.dateFormat = 'dd M yy'; /** * Sets the date for each select with the date selected with datepicker */ $('input.ui-date-text').live("change", function() { var sels = $(this).siblings("select:lt(3)"); var d = $.datepicker.parseDate($.datepicker._defaults.dateFormat, $(this).val() ); $(sels[0]).val(d.getFullYear()); $(sels[1]).val(d.getMonth() + 1); $(sels[2]).val(d.getDate()); }); /** * Replaces the date or datetime field with jquey-ui datepicker */ $('.date, .datetime').each(function(i, el) { var input = document.createElement('input'); $(input).attr({'type': 'text', 'class': 'ui-date-text'}); // Insert the input:text before the first select $(el).find("select:first").before(input); $(el).find("select:lt(3)").hide(); // Set the input with the value of the selects var values = []; $(input).siblings("select:lt(3)").each(function(i, el) { var val = $(el).val(); if(val != '') values.push(val); }); if( values.length > 1) { d = new Date(values[0], parseInt(values[1]) - 1, values[2]); $(input).val( $.datepicker.formatDate($.datepicker._defaults.dateFormat, d) ); } $(input).datepicker(); }); });
-
∞ Formtastic datetime
class MyCustomFormBuilder < ::Formtastic::SemanticFormBuilder def date_or_datetime_input(method, options) position = { :year => 1, :month => 2, :day => 3, :hour => 4, :minute => 5, :second => 6 } i18n_date_order = ::I18n.t(:order, :scope => [:date]) i18n_date_order = nil unless i18n_date_order.is_a?(Array) inputs = options.delete(:order) || i18n_date_order || [:year, :month, :day] time_inputs = [:hour, :minute] time_inputs << [:second] if options[:include_seconds] list_items_capture = "" hidden_fields_capture = "" # Gets the datetime object. It can be a Fixnum, Date or Time, or nil. datetime = @object ? @object.send(method) : nil html_options = options.delete(:input_html) || {} input_ids = [] (inputs + time_inputs).each do |input| input_ids << input_id = generate_html_id(method, "#{position[input]}i") field_name = "#{method}(#{position[input]}i)" if options[:"discard_#{input}"] break if time_inputs.include?(input) hidden_value = datetime.respond_to?(input) ? datetime.send(input.to_sym) : datetime hidden_fields_capture << template.hidden_field_tag("#{@object_name}[#{field_name}]", (hidden_value || 1), :id => input_id) else begin # version 0.9.7 and up opts = strip_formtastic_options(options).merge(:prefix => @object_name, :field_name => field_name, :default => datetime) rescue # version 0.9.1 opts = set_options(options).merge(:prefix => @object_name, :field_name => field_name) end item_label_text = ::I18n.t(input.to_s, :default => input.to_s.humanize, :scope => [:datetime, :prompts]) list_items_capture << template.send(:"select_#{input}", datetime, opts, html_options.merge(:id => input_id)) end end hidden_fields_capture << self.label(method, options_for_label(options)) << list_items_capture end end
-
∞ Rails 3 app from edge
# From pastie http://pastie.org/684600 by José Valim # First, clone Rails master git clone git://github.com/rails/rails cd rails # Bundle Rails master dependencies gem install bundler gem bundle # Generate a fresh developer app in a folder named rails inside your rails checkout: cd railties rake dev # Configure the new fresh repo to use rails edge by changing config/boot.rb to: environment = File.expand_path('../../../vendor/gems/environment', __FILE__) require environment require 'rails'
-
∞ Rails: Helper method for adding word breaks to pesky long URLs
module ApplicationHelper # Word Break Helper: great for things like those pesky long URLs def wbr(str) str.split('').join('​') end end # Use: <%= wbr 'http://AReallyLongAndPeskyUrlThatGoesOnAndOn.com/how-about-some-more-url/yes-please/thank-you' %>
-
∞ Rails: Use default_scope to set up default find conditions such as order
class MyModel < ActiveRecord::Base default_scope :order => 'created_at desc' end
-
∞ in console displays activerecord's sql operations
ActiveRecord::Base.logger = Logger.new(STDOUT)
-
∞ Hash to Class (javascript-like!)
# Converts a hash to an instance of a class # From http://pullmonkey.com/2008/1/6/convert-a-ruby-hash-into-a-class-object class Hashit def initialize(hash) hash.each do |k,v| self.instance_variable_set("@#{k}", v) ## create and initialize an instance variable for this key/value pair self.class.send(:define_method, k, proc{self.instance_variable_get("@#{k}")}) ## create the getter that returns the instance variable self.class.send(:define_method, "#{k}=", proc{|v| self.instance_variable_set("@#{k}", v)}) ## create the setter that sets the instance variable end end end
-
∞ raise error for debugging
raise params.inspect
-
∞ Run DB Migrate on production
rake db:migrate RAILS_ENV=production
-
∞ Rails SVN:Ignore DB setup (destructive to the DB!)
svn remove db/*.sqlite3 svn commit -m 'removing all tmp artifacts from subversion' svn propset svn:ignore "*.sqlite3" db/ svn update db/ svn commit -m "ignore db/*.sqlite3 content from now on"
-
∞ Rails SVN:Ignore setup (nondestructive)
svn remove log/* svn commit -m 'removing all log files from subversion' svn propset svn:ignore "*.log" log/ svn update log/ svn commit -m 'Ignoring all files in /log/ ending in .log' svn remove tmp/* svn commit -m 'removing all tmp artifacts from subversion' svn propset svn:ignore "*" tmp/ svn update tmp/ svn commit -m "ignore tmp/ content from now on"
-
∞ call protected with_exclusive_scope
Category.send(:with_exclusive_scope) { Category.find(:all) }
-
∞ install rails on ubuntu
#!/bin/bash # Install Ruby packages sudo aptitude install ruby rdoc irb ri rubygems libopenssl-ruby ruby-dev build-essential # Add gem binaries to the bash PATH echo "export PATH=/var/lib/gems/1.8/bin:\$PATH" | sudo tee -a /etc/bash.bashrc # Install Rails sudo gem install rails # Install SQLite3 support (optional) sudo aptitude install libsqlite3-0 libsqlite3-dev sudo gem install sqlite3-ruby # Install MySQL support (optional) sudo aptitude install libmysql-ruby mysql-server mysql-client \ mysql-client-dev mysql-query-browser sudo gem install mysql # Install Mongrel server (optional) sudo gem install mongrel # Enable IRB autocompletion echo 'require "irb/completion"' >> $HOME/.irbrc
-
∞ create rails application with git repository
#!/bin/sh # Create Rails application rails $* # Goto the application cd $1 # Initialize git repository git init # Create ignore list touch log/.gitignore touch tmp/.gitignore tee .gitignore <<END log/*.log tmp/**/* db/*.sqlite3 doc/api doc/app END # Create pre-commit hook tee .git/hooks/pre-commit <<END rm .git/hooks/*.sample #!/bin/sh rake test END chmod a+x .git/hooks/pre-commit # Create empty database files rake db:migrate # Add dir to repository git add . # Commit it git commit -m "Created empty Rails application" # Install jRails plugin (replace Prototype for jQuery) script/plugin install http://ennerchi.googlecode.com/svn/trunk/plugins/jrails git add vendor public/javascripts/*.js git rm public/javascripts/controls.js public/javascripts/dragdrop.js \ public/javascripts/effects.js public/javascripts/prototype.js git commit -a -m "Installed jRails plugin (replaced Prototype for jQuery)" # Download Blueprint CSS framework mkdir -p public/stylesheets/blueprint for f in ie print screen; do wget http://github.com/joshuaclayton/blueprint-css.git/blueprint/$f.css \ -O public/stylesheets/blueprint/$f.css done touch public/stylesheets/main.css git add public/stylesheets git commit -m "Installed blueprint CSS framework" # Basic Blueprint layout mkdir -p app/views/layouts wget http://dl.getdropbox.com/u/550278/application.html.erb \ -O app/views/layouts/application.html.erb echo "<h3>Sidebar</h3>" | tee app/views/layouts/_sidebar.html.erb git add app/views/layouts git commit -m "Created basic layout" # Create home controller script/generate controller home index git add app/controllers/home_controller.rb app/helpers/home_helper.rb \ app/views/home test/functional/home_controller_test.rb test/unit/helpers git rm public/index.html tee config/routes.rb <<END ActionController::Routing::Routes.draw do |map| map.root :controller => "home" map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end END git add config/routes.rb git commit -m "Created Home controller"
-
∞ restart a Rails Web Application on DreamHost.
# restart a Rails Web Application on DreamHost. this requires that you've # enabled mod_rails (Passenger) support for the app in the DreamHost panel $ touch /your_web_app_directory/tmp/restart.txt # Passenger looks for a file tmp/restart.txt and if it exists, it reloads # your app, and refreshes all your files then deletes the tmp/restart.txt file # The other way to force a restart is through the dreamhost panel: # Domains > Manage Domains > Edit your-app.domain.com # >> submit the form through the "fully host this application" button.
-
∞ Suppress missing images in development mode, place in .rb file in your initializers folder
# originally found at http://www.williambharding.com/blog/rails/rails-fix-slow-loads-in-development-when-images-missing/ if RAILS_ENV == 'development' module ActionView module Helpers #:nodoc: module AssetTagHelper def path_to_image(source) original_tag = ImageTag.new(self, @controller, source).public_path # Create the file below or simply point it to your own placeholder image_location = "/images/trash_can.gif" if(image_location && (image_location.index("http") || File.exists?(RAILS_ROOT + "/public" + image_location.gsub(/\?.*/, '')))) image_location else default_image end end end end end end



Beginning PHP and MySQL: From Novice to Professional