Latest 100 public
snipts » rails
showing 1-20 of 42 snipts for rails
-
∞ Rails 3 IP Geo Location
# Ruby on Rails: Geo Location Gem # Track where your users are around the globe with the Rails 3 Geo Location Gem. Use hostip.info's free service or get a paid account at maxmind.com. I've found the MaxMind response time to be excellent and the data is more complete accurate - but in a pinch or with a low budget, HostIP looks like a great solution as well. # == GitHub http://github.com/chrisyour/geo_location # == Install gem install geo_location # == Use: HostIP (free) # Configuration (config/initializers/geo_location_config.rb) unless GeoLocation == nil # Use HostIP (free) GeoLocation::use = :hostip end # Example ip = GeoLocation.find('24.24.24.24') # => {:city=>"Liverpool", :region=>"NY", :country=>"US", :latitude=>"43.1059", :longitude=>"-76.2099"} puts ip[:city] # => Liverpool puts ip[:region] # => NY puts ip[:country] # => US puts ip[:latitude] # => 43.1059 puts ip[:longitude] # => -76.2099 # == Use: MaxMind (paid) # Configuration (config/initializers/geo_location_config.rb) unless GeoLocation == nil # Use Max Mind (paid) # For more information visit: http://www.maxmind.com/app/city GeoLocation::use = :maxmind GeoLocation::key = 'YOUR MaxMind.COM LICENSE KEY' # This location will be used while you develop rather than hitting the maxmind.com api # GeoLocation::dev = 'US,NY,Jamaica,40.676300,-73.775200' # IP: 24.24.24.24 end # Example ip = GeoLocation.find('24.24.24.24') # => {:city=>"Jamaica", :region=>"NY", :country=>"US", :latitude=>"40.676300", :longitude=>"-73.775200"} puts ip[:city] # => Jamaica puts ip[:region] # => NY puts ip[:country] # => US puts ip[:latitude] # => 40.676300 puts ip[:longitude] # => -73.775200
-
∞ rails basic validation
validates_presence_of :mode, :distance, :email validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create validates_numericality_of :distance, :on => :create validates_format_of :phone, :message => "must be a valid telephone number.", :with => /^[\(\)0-9\- \+\.]{10,20} *[extension\.]{0,9} *[0-9]{0,5}$/ validates_uniqueness_of :name, :case_sensitive => false, :on => :create validates_length_of :zip, :maximum=>5
-
∞ [Rails] .gitignore
config/database.yml doc/api doc/app log/*.log tmp/**/*
-
∞ Another solution to RVM Ubuntu Rails error
$ rvm uninstall 1.9.1 $ rvm install 1.9.1 --with-readline-dir=$rvm_path/.rvm/usr
-
∞ Generate permalinks after adding permalink_fu
# Generate permalinks after adding permalink_fu Post.find(:all).each(&:save)
-
∞ reprocess paperclip thumbnails
# Given Photo has_attached_file # `image` is the has_attached_file name Photo.find(:all).each { |a| a.image.reprocess!; a.save }
-
∞ 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"


