Latest 100 public
snipts » ruby
showing 1-20 of 94 snipts for ruby
-
∞ 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
-
∞ Checks whether ssh keys in keydir are broken in a gitosis-admin repository.
#!/usr/bin/env ruby # Script by Camillo Bruni, Oscar Nierstrasz, Niko Schwarz, 2010 # This script checks whether any incoming commit # has invalid ssh keys in the keydir directory. That is useful # for gitosis-admin repositories, as gitosis crashes hard # if faulty keys reside in the keydir. # Install it in .git/hooks/update, make sure it belongs to the git user # and is set to be executable. require "base64" def valid_public_ssh_key?(key) match = /^(\S+) (\S+=+) (\S+)\n*/.match(key) return false if match.nil? type = match[1] key_string = match[2] comment = match[3] data = Base64.decode64(key_string) int_len = 4 str_len = data[0..int_len-1].unpack('N')[0] return data[int_len..int_len+str_len-1] == type end def valid_key_file?(file) line_number = 1 invalid_lines = [] `git show #{ARGV[2]}:#{file}`.each_line { |line| if not valid_public_ssh_key?(line) invalid_lines.push(line_number) end line_number+=1 } return "" if invalid_lines.empty? return "\033[0;31m Invalid ssh keys on lines #{invalid_lines.inspect} in #{file}\033[0m\n" end files = `git diff #{ARGV[1]} #{ARGV[2]} --name-only --diff-filter=AM -z` errors = files.split("\0").select{|file_name| file_name.match(/^keydir\//)} \ .map { |file_name| valid_key_file?(file_name)}.join("") puts errors exit errors.empty? ? 0 : -1
-
∞ HTML5 ruby support for all browsers
/* HTML5 ruby support for all browsers, by @jcayzac. * Tested in IE6, IE7, Firefox 3.6, Firefox 4, Chromium 6 & Opera 10.61. */ ruby { padding-top:0.7em; position:relative; /* cross-browser "inline-box": */ vertical-align: baseline; display:-moz-inline-box; display: inline-block; *display:inline; zoom:1; } ruby rt {font-size:60%;position:absolute;display:block;top:0;left:0;right:0;text-align:center;} ruby rp {display:none;}
-
∞ CTRL-C Quit during Ruby Net::HTTP Request
trap('SIGINT') { http.finish; return } -
∞ Force Mechanize to return HTTP Success when condition is met in Ruby
require 'rubygems' require 'uri' require 'mechanize' require 'rack/utils' # so you can do `params.inspect` throughout Mechanize class NilClass; def search(*args); []; end; end Mechanize::Chain::PostConnectHook.class_eval do def handle(ctx, params) headers = params[:response].to_hash if headers.has_key?("location") headers["location"].each do |location| url = URI.parse(location) if url.host == "localhost" && url.port == 4567 params[:res_klass] = Net::HTTPSuccess end end end p params.keys #=> [:res_klass, :uri, :response_body, :referer, :response, :agent, :verb, :redirects, :connection, :params, :request, :headers] p params[:uri] #=> #<URI::HTTPS:0x1aa0810 URL:https://somesite.com?key=value> p params[:response] #=> #<Net::HTTPFound 302 Found readbody=true> p params[:response].to_hash #=> {"location"=>["http://somesite.com"], "expires"=>["Sat, 01 Jan 2000 00:00:00 GMT"], "content-type"=>["text/html; charset=utf-8"], "date"=>["Mon, 16 Aug 2010 04:31:13 GMT"], "content-length"=>["0"], "cache-control"=>["private, no-cache, no-store, must-revalidate"], "x-cnection"=>["close"], "pragma"=>["no-cache"]} super(ctx, params) end end agent = Mechanize.new page = agent.get("https://somesite.com") # ... tons of redirects, # then finally we find a match in our `handle` method above, # and reset the `params[:res_klass]` to `Net::HTTPSuccess`. # that is a hack to say basically, # "return the page, we found what we want" location = URI.parse(page.response.to_hash["location"].to_a.first) params = Rack::Utils.parse_query(location.query)
-
∞ Regular Expression to Parse Ruby Log Messages
# parse ruby log message # customize as needed LOG_EXPRESSION = /([\w]+),\s+\[([^\]\s]+)\s+#([^\]]+)]\s+(\w+)\s+--\s+(\w+)?:\s+(.+)/ # sample log output from this call: # logger.info("Ubiquitously") { "[dequeud] #{JSON.generate(params)}"} string = 'I, [2010-08-15T16:16:46.142801 #81977] INFO -- Ubiquitously: {"title":"Google","url":"google.com","tags":"search, google, api","services":["meta_filter","mixx"],"description":"a search engine!"}' sample_output.gsub(LOG_EXPRESSION) do |match| severity = $1 date = $2 # Time.parse(date) pid = $3 label = $4 app = $5 message = $6 end
-
∞ Return Array of Overridden Methods in Ruby Subclasses
# thanks to the answer here: # http://stackoverflow.com/questions/3488203/how-do-i-see-where-in-the-class-hierarchy-a-method-was-defined-and-overridden-in class Object def self.overridden_methods(parent_class = Object, within_tree = true) if within_tree defined_methods = ancestors[0..ancestors.index(parent_class) - 1].map { |object| object.instance_methods(false) }.flatten.uniq parent_methods = superclass.instance_methods else defined_methods = instance_methods(false) parent_methods = parent_class.instance_methods end defined_methods & parent_methods end def overridden_methods(parent_class = Object, within_tree = true) self.class.overridden_methods(parent_class, within_tree) end def self.overrides?(method, parent_class = Object, within_tree = true) overridden_methods(parent_class, within_tree).include?(method.to_s) end def overrides?(method, parent_class = Object, within_tree = true) self.class.overrides?(method, parent_class, within_tree) end end class ParentModel < Object def save; end end class ChildModel < ParentModel def save; end def create; end def to_s; end end class AnotherChildModel < ParentModel def save; end end class GrandChildModel < ChildModel def create; end end # what have you overridden from the base `Object` class p ParentModel.overridden_methods(Object) #=> [] p ParentModel.overridden_methods(Object, false) #=> [] p ChildModel.overridden_methods(Object) #=> ["to_s", "save"] p ChildModel.overridden_methods(Object, false) #=> ["to_s"] p ChildModel.overridden_methods(ParentModel) #=> ["to_s", "save"] p ChildModel.overridden_methods(ParentModel, false) #=> ["to_s", "save"] p AnotherChildModel.overridden_methods(Object) #=> ["save"] p AnotherChildModel.overridden_methods(Object, false) #=> [] p AnotherChildModel.overridden_methods(ParentModel) #=> ["save"] p AnotherChildModel.overridden_methods(ParentModel, false) #=> ["save"] p GrandChildModel.overridden_methods(Object) #=> ["create", "to_s", "save"] p GrandChildModel.overridden_methods(Object, false) #=> [] p GrandChildModel.overridden_methods(ParentModel) #=> ["create", "to_s", "save"] p GrandChildModel.overridden_methods(ParentModel, false) #=> [] p GrandChildModel.overridden_methods(ChildModel) #=> ["create"] p GrandChildModel.overridden_methods(ChildModel, false) #=> ["create"] # note, this probably won't work with modules overriding methods, it just needs to be tweaked a little more
-
∞ Print All Ruby Classes in Array
ObjectSpace.each_object(Class).to_a
-
∞ Ruby Metaprogramming - Subclassable Callback Module
require 'rubygems' require 'active_model' # use this if you want to create before and after filters around a commonly used # method, but still want to define the method in subclasses. module SubclassableCallbacks def self.included(base) base.extend ClassMethods end module ClassMethods attr_accessor :subclassable_callbacks def subclassable_callbacks(*methods) @subclassable_callbacks ||= [] unless methods.empty? @subclassable_callbacks = @subclassable_callbacks.concat(methods).flatten.compact.map(&:to_sym).uniq define_model_callbacks *methods class_eval do methods.each do |variable| define_method "implementation_#{variable.to_s}" do; end define_method variable do send("_run_#{variable.to_s}_callbacks") do send("implementation_#{variable.to_s}") end end alias_method "superclass_#{variable.to_s}", variable end end end @subclassable_callbacks end end def self.override ObjectSpace.each_object(Class) do |object| if object.ancestors.include?(SubclassableCallbacks) object.class_eval do methods = object.subclassable_callbacks last_index = object.superclass.ancestors.index(SubclassableCallbacks) if last_index && last_index > 0 superclass_methods = object.superclass.ancestors[0..last_index - 1].map(&:subclassable_callbacks) methods = methods.concat(superclass_methods).flatten.uniq end methods.each do |name| alias_method "subclass_#{name}", "#{name}" alias_method "implementation_#{name}", "subclass_#{name}" alias_method "#{name}", "superclass_#{name}" end end end end end end class BaseModel extend ActiveModel::Callbacks include SubclassableCallbacks subclassable_callbacks :save before_save { puts "[save:before]"} after_save { puts "[save:after]"} end class SomeModel < BaseModel def save puts "[saving some_model...]" true end end class AnotherModel < BaseModel def save puts "[saving another_model...]" true end end SubclassableCallbacks.override SomeModel.new.save #=> [save:before] #=> [saving some_model...] #=> [save:after] AnotherModel.new.save #=> [save:before] #=> [saving another_model...] #=> [save:after]
-
∞ Regular Expression to Create URL Permutations in Ruby
# return 4 urls, with and without trailing slash, with and without www # useful for matching urls passed as params into some function, # "does this url exist?"... need to make sure you check permutations def url_permutations(url) url, params = url.split("?") # without_trailing_slash, with www a = url.gsub(/\/$/, "").gsub(/http(s)?:\/\/([^\/]+)/) do |match| protocol = "http#{$1.to_s}" domain = $2 domain = "www.#{domain}" if domain.split(".").length < 3 # www.google.com == 3, google.com == 2 "#{protocol}://#{domain}" end # with_trailing_slash, with www b = "#{a}/" # without_trailing_slash, without www c = a.gsub(/http(s)?:\/\/www\./, "http#{$1.to_s}://") # with_trailing_slash, without www d = "#{c}/" [a, b, c, d].map { |url| "#{url}?#{params}"} end puts url_permutations("http://google.com/search?q=http://google.com").inspect #=> [ "http://www.google.com/search?q=http://google.com", "http://www.google.com/search/?q=http://google.com", "http://google.com/search?q=http://google.com", "http://google.com/search/?q=http://google.com" ]
-
∞ Recursively Symbolize Keys in Ruby
class Hash def recursively_symbolize_keys! self.symbolize_keys! self.values.each do |v| if v.is_a? Hash v.recursively_symbolize_keys! elsif v.is_a? Array v.recursively_symbolize_keys! end end self end end class Array def recursively_symbolize_keys! self.each do |item| if item.is_a? Hash item.recursively_symbolize_keys! elsif item.is_a? Array item.recursively_symbolize_keys! end end end end
-
∞ Ruby Trim Array to Words Less than Character Count
class Array def chop(separator = "", max = 40) result = [] self.each do |word| break if (result.join(separator).length + word.length > max) result << word result end result end end
-
∞ Text to speach using Ruby, SInatra and Espeak
require 'rubygems' require 'sinatra' require 'espeak-ruby' include ESpeak get '/tts' do file = "file_#{Time.now}.mp3" espeak( file,params ) [ 200, { "Content-type" => "audio/mpeg" }, File.read( file ) ] end
-
∞ Receiving Xmpp messages with ruby
require 'rubygems' require 'xmpp4r-simple' include Jabber @user = Simple.new('JID', 'PASSWORD') @friends = @user.roster @user.received_messages do |message| puts message + " from : " +message.from end
-
∞ Config.ru for my homesite
require 'rubygems' require 'application.rb' run Sinatra::Application
-
∞ enconde decode files base 64
# Encode a file to base64 encoding: File.open("output_file","w"){|file| file.write [open("link_to_file").string].pack("m")} # Decode base64 encoded file: File.open('original', 'wb') {|file| file << (IO.readlines('output_file').to_s.unpack('m')).first }
-
∞ RVM Readline Error
#When I tried to use Rails console with 'rails c' or 'rails console' #I got some ugly output: /home/myHome/.rvm/rubies/ruby-1.9.1-p378/lib/ruby/1.9.1/irb/completion.rb:9:in `require': no such file to load -- readline (LoadError) from /home/myHome/.rvm/rubies/ruby-1.9.1-p378/lib/ruby/1.9.1/irb/completion.rb:9:in `<top (required)>' from /home/myHome/.rvm/gems/ruby-1.9.1-p378/gems/railties-3.0.0.beta/lib/rails/commands/console.rb:3:in `require' from /home/myHome/.rvm/gems/ruby-1.9.1-p378/gems/railties-3.0.0.beta/lib/rails/commands/console.rb:3:in `<top (required)>' from /home/myHome/.rvm/gems/ruby-1.9.1-p378/gems/railties-3.0.0.beta/lib/rails/commands.rb:32:in `require' from /home/myHome/.rvm/gems/ruby-1.9.1-p378/gems/railties-3.0.0.beta/lib/rails/commands.rb:32:in `<top (required)>' from /home/myHome/Publiczny/f44/script/rails:10:in `require' from /home/myHome/Publiczny/f44/script/rails:10:in `<main>' #It appears I was missing some ssl libraries. So I removed my rvm completely (although I think it wasn't #necessary), and installed some libraries: sudo apt-get install openssl libssl-dev libreadline5-dev zlib1g-dev #then I reinstalled rvm and ruby et voila
-
∞ 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
-
∞ 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


