IMPORTANT!

Snipt is going open source. We've toyed with this idea for quite a while, and have finally decided it's the right way to move forward.

A few things:
  • The entire Snipt source code will be released on GitHub under the 3-clause BSD License on Friday, September 10th.
  • While we'd like to think we're perfect, we realize we're only human. By open sourcing the software that runs this website, certain bugs or security flaws may be discovered that could compromise the privacy of your snipts.
  • Only the Lion Burger team will be able to push commits to the Snipt.net site. Contributors should send a pull request to add new features or submit patches.
  • By using this site, you agree not to be too angry or take any legal action against Lion Burger should this whole thing go up in flames some day.
  • Follow us on Twitter for updates.
I agree, close this message
Sign up to create your own snipts, or login.

Latest 100 public snipts » ruby The latest public ruby snipts.

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
    

    copy | embed

    0 comments - tagged in  posted by chrisyour on Aug 24, 2010 at 8:39 p.m. EDT
  • 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
    

    copy | embed

    0 comments - tagged in  posted by nikoschwarz on Aug 19, 2010 at 10:35 a.m. EDT
  • 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;}
    

    copy | embed

    0 comments - tagged in  posted by w00kie on Aug 18, 2010 at 2:57 a.m. EDT
  • CTRL-C Quit during Ruby Net::HTTP Request
    trap('SIGINT') { http.finish; return }
    

    copy | embed

    0 comments - tagged in  posted by viatropos on Aug 17, 2010 at 6:49 p.m. EDT
  • 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)
    

    copy | embed

    0 comments - tagged in  posted by viatropos on Aug 16, 2010 at 12:40 a.m. EDT
  • 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
    

    copy | embed

    0 comments - tagged in  posted by viatropos on Aug 15, 2010 at 5:39 p.m. EDT
  • 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
    

    copy | embed

    0 comments - tagged in  posted by viatropos on Aug 15, 2010 at 1:46 p.m. EDT
  • Print All Ruby Classes in Array
    ObjectSpace.each_object(Class).to_a
    

    copy | embed

    0 comments - tagged in  posted by viatropos on Aug 15, 2010 at 12:29 a.m. EDT
  • 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]
    

    copy | embed

    0 comments - tagged in  posted by viatropos on Aug 15, 2010 at 12:21 a.m. EDT
  • 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"
    ]
    

    copy | embed

    0 comments - tagged in  posted by viatropos on Aug 12, 2010 at 12:51 p.m. EDT
  • 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
    

    copy | embed

    0 comments - tagged in  posted by viatropos on Aug 10, 2010 at 12:35 p.m. EDT
  • 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
    

    copy | embed

    0 comments - tagged in  posted by viatropos on Aug 10, 2010 at 11:58 a.m. EDT
  • 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
    
      
    

    copy | embed

    0 comments - tagged in  posted by hkairi on Jun 22, 2010 at 8:30 a.m. EDT
  • 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
    

    copy | embed

    0 comments - tagged in  posted by hkairi on Jun 22, 2010 at 7:02 a.m. EDT
  • Config.ru for my homesite
    require 'rubygems'
    require 'application.rb'
    
    run Sinatra::Application
    

    copy | embed

    0 comments - tagged in  posted by Loyolny on May 17, 2010 at 4:52 p.m. EDT
  • 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 }
    

    copy | embed

    0 comments - tagged in  posted by boriscy on Apr 28, 2010 at 9:52 a.m. EDT
  • 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
    

    copy | embed

    0 comments - tagged in  posted by Loyolny on Apr 09, 2010 at 5:01 p.m. EDT
  • 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 }
    

    copy | embed

    0 comments - tagged in  posted by christopherstyles on Mar 30, 2010 at 11:18 a.m. EDT
  • 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
    

    copy | embed

    0 comments - tagged in  posted by cbeier on Mar 08, 2010 at 7:00 a.m. EST
  • 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
    

    copy | embed

    0 comments - tagged in  posted by lear64 on Feb 23, 2010 at 11:07 a.m. EST
Sign up to create your own snipts, or login.