Sign up to create your own snipts, or login.

Public snipts » ruby The latest public ruby snipts.

showing 1-20 of 76 snipts for ruby
  • 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
  • module_function
    module Math
      def sin(x)
        # ...
      end
      module_function :sin
    end
    
    Math.sin(1)
    include Math
    sin(2)
    

    copy | embed

    0 comments - tagged in  posted by jhlinuz on Feb 10, 2010 at 3:00 p.m. EST
  • Use '[' and ']' for regexps
    # This will find the first numbers in an ip
    
    ip = "123.33.1.200"
    ip[/(\d+).(\d+).(\d+).(d+)/]
    
    puts "First: #{$1}"
    puts "Second: #{$2}"
    # . . .
    

    copy | embed

    0 comments - tagged in  posted by jhlinuz on Jan 24, 2010 at 7:46 a.m. EST
  • Convert erb to haml
    #!/usr/bin/ruby -w
    #
    # Script: erb2haml
    # Author: Chip Castle - http://chipcastle.com
    # Date:   16jan2010
    #
    Dir.foreach(".") do |file|
      next if /^\./.match(file)
      if File.extname(file).eql?('.erb')
        base = File.basename(file, '.erb')
        puts "Converting #{file} to HAML #{base}.haml"
        system "html2haml #{file} > #{base}.haml"
      else
        puts "Skipping #{file}"
      end
    end
    

    copy | embed

    0 comments - tagged in  posted by chipcastle on Jan 16, 2010 at 10:43 p.m. EST
  • anak-ayam-kotek-kotek.rb - A simple ruby code for singing simple substraction mathematical problem.
    # Ask Them How Many Anak Ayam Will Get Counted Down!
    anak_ayam = gets.chomp    
    if anak_ayam.is_a?(Integer) == true
      puts ''
    else
      puts ''
    # Now Get Down With It!
    while anak_ayam != 0
      puts 'Tek Kotek Kotek Kotek'
      puts 'Anak ayam turun '+anak_ayam.to_s+'.'
      puts 'Tek Kotek Kotek Kotek'                 
      anak_ayam = anak_ayam.to_i - 1  
      puts 'Mati satu tinggalah '+anak_ayam.to_s+''
      puts ''
    # If We Have One Anak Ayam Running Left!
      if anak_ayam == 1            
        puts ''
        puts 'Tek Kotek Kotek Kotek' 
        puts 'Anak ayam turunlah '+anak_ayam.to_s+'.'
        anak_ayam = anak_ayam - 1      
        puts 'Tek Kotek Kotek Kotek'     
        puts 'Mati satu tinggalah '+anak_ayam.to_s+''          
      else                     
      end
    end
    
    puts ''                  
    end
    

    copy | embed

    0 comments - tagged in  posted by gerryleonugroho on Jan 13, 2010 at 3:41 a.m. EST
  • twitter gem & ruby
    #!/usr/local/bin/ruby
    
    require 'rubygems'
    require 'twitter'
    
    httpauth = Twitter::HTTPAuth.new('UserName', 'Password')
    
    client = Twitter::Base.new(httpauth)
    puts client.friends_timeline[0].text 
    

    copy | embed

    0 comments - tagged in  posted by betahost on Jan 07, 2010 at 2:19 a.m. EST
  • Prepends " - " to each line
    ruby -n -e 'puts " - " + $_' bla.txt 
    

    copy | embed

    0 comments - tagged in  posted by nes1983 on Dec 09, 2009 at 8:06 a.m. EST
  • All erb files in dir to haml
    #! /bin/bash
    # erb2haml
    # by Michelangelo Altamore
     
    # Convert all files having a html.erb extension in the current dir
    # to haml format with html.haml extension. HAML gem must be installed.
    
    for erb_file in `find . -name *.html.erb`; do
    if [ -f $erb_file ] ; then
    name=${erb_file%.html.erb};
        html2haml  > .html.haml;
      fi;
    done
    

    copy | embed

    1 comment - tagged in  posted by kevinvaldek on Dec 04, 2009 at 8:02 a.m. EST
  • For my friend.
    #!/usr/bin/env ruby
    
    class LinkedList
      def initialize(array=[])
        @array = array
        @current_index = 0
        @max_size = array.size
      end
      
      def next
        @current_index += 1 if @current_index < @max_size
        @current_index = 0 if @current_index >= @max_size
        return current
      end
      
      def prev
        @current_index -= 1 if @current_index > 0
        @current_index = @array.size - 1 if @current_index == 0
        return current
      end
      
      def current
        return @array[@current_index]
      end
    end
    
    array = %w"Apple Microsoft Nokia Motorola Google"
    link = LinkedList.new(array)
    puts "Current: #{link.current}"
    puts "Next: #{link.next}"
    puts "Current: #{link.current}"
    puts "Next: #{link.next}"
    puts "Current: #{link.current}"
    puts "Next: #{link.next}"
    puts "Current: #{link.current}"
    puts "Next: #{link.next}"
    puts "Current: #{link.current}"
    puts "Next: #{link.next}"
    puts "Current: #{link.current}"
    puts "Next: #{link.next}"
    puts "Current: #{link.current}"
    puts "Next: #{link.next}"
    puts "Current: #{link.current}"
    puts "Next: #{link.next}"
    puts "Current: #{link.current}"
    puts "Next: #{link.next}"
    puts "Current: #{link.current}"
    puts "Next: #{link.next}"
    puts "Current: #{link.current}"
    puts "Prev: #{link.prev}"
    puts "Current: #{link.current}"
    puts "Prev: #{link.prev}"
    puts "Current: #{link.current}"
    puts "Prev: #{link.prev}"
    puts "Current: #{link.current}"
    puts "Prev: #{link.prev}"
    puts "Current: #{link.current}"
    puts "Prev: #{link.prev}"
    puts "Current: #{link.current}"
    puts "Prev: #{link.prev}"
    puts "Current: #{link.current}"
    puts "Prev: #{link.prev}"
    puts "Current: #{link.current}"
    puts "Prev: #{link.prev}"
    puts "Current: #{link.current}"
    puts "Prev: #{link.prev}"
    puts "Current: #{link.current}"
    

    copy | embed

    0 comments - tagged in  posted by hechian on Nov 30, 2009 at 9:23 a.m. EST
  • Generic GAE Rakefile
    require 'rubygems'
    require 'appengine-sdk'
    
    BASE = File.expand_path(File.dirname(__FILE__))
    SRC = BASE + '/src'
    LIB = BASE + '/WEB-INF/lib'
    SERVLET = AppEngine::SDK::SDK_ROOT + '/lib/shared/geronimo-servlet_2.5_spec-1.2.jar'
    APIS = AppEngine::SDK::API_JAR
    WEB_INF_CLASSES = BASE + '/WEB-INF/classes'
    
    def jvmc(compiler, *files)
      chdir(SRC) do
        files = files.map { |file| file.pathmap("%{^#{SRC}/,}p") }.join ' '
        dest = "-d #{WEB_INF_CLASSES}"
        mkdir_p WEB_INF_CLASSES
        libs = Dir[LIB + '/*.jar'].select { |path| File.file?(path) }
        orig_classpath = ENV['CLASSPATH']
        ENV['CLASSPATH'] ||= ''
        ENV['CLASSPATH'] += ['', SERVLET, APIS, WEB_INF_CLASSES].concat(libs).join(File::PATH_SEPARATOR)
        puts "sh %{#{compiler} #{dest} #{files}}"
        sh %{#{compiler} #{dest} #{files}}
        ENV['CLASSPATH'] = orig_classpath
      end
    end
    
    def class_file(src_file)
      src_file.pathmap("%{^#{SRC},#{WEB_INF_CLASSES}}X.class")
    end
    
    task :java_sources do
      java_sources = FileList[SRC + '/**/*.java']
      unless java_sources.inject(true) { |mem, file|
          mem && uptodate?(class_file(file), [file]) }
        jvmc('javac', java_sources)
      end
    end
    
    task :duby_sources do
      duby_sources = FileList[SRC + '/**/*.duby']
      unless duby_sources.inject(true) { |mem, file|
          mem && uptodate?(class_file(file), [file]) }
        jvmc('dubyc', duby_sources)
      end
    end
    
    task :compile => [:java_sources, :duby_sources]
    
    task :clean do
      rm_rf WEB_INF_CLASSES
    end
    
    task :server => :compile do
      sh "dev_appserver.rb #{BASE}"
    end
    
    task :upload => [:clean, :compile] do
      sh "appcfg.rb update #{BASE}"
    end
    
    task :default => :server
    

    copy | embed

    0 comments - tagged in  posted by hvis on Nov 22, 2009 at 6:09 p.m. EST
  • Buffered IO from read-only stream
    # Stole it from http://bit.ly/7COJAf, fixed a bug on line 26 (- -> +)
    
    require 'stringio'
    
    class BufferedIO
      def initialize(io)
        @buff = StringIO.new
        @source = io
      end
    
      def read(x=nil)
        to_read = x ? to_read = x + @buff.pos - @buff.size : nil
        _append(@source.read(to_read)) if !to_read or to_read > 0
        @buff.read(x)
      end
    
      def pos=(x)
        read(x - @buff.pos) if x > @buff.size
        @buff.seek x
      end
    
      def seek(x, whence=IO::SEEK_SET)
        case whence
          when IO::SEEK_SET then self.pos=(x)
          when IO::SEEK_CUR then self.pos=(@buff.pos + x)
          when IO::SEEK_END then read; self.pos=(@buff.size + x)
          # Note: SEEK END reads all the socket data.
        end
        pos
      end
    
      # Some methods can simply be delegated to the buffer.
      ["pos", "rewind", "tell", "eof?", "readline"].each do |m|
        module_eval "def #{m}\n@buff.#{m}\nend"
      end
    
      private
    
      def _append(s)
        @buff << s
        @buff.seek -s.size, IO::SEEK_CUR
      end
    end
    

    copy | embed

    0 comments - tagged in  posted by hvis on Nov 21, 2009 at 5:39 p.m. EST
  • general cucumber paths (restful)
    # Request in the feature -> ... the user show "foo" page by "login"
    
    # -> features/support/paths.rb
    when /^the (.*) (edit|show|overview|new)( "([^\"]*)")? page by "([^\"]*)"$/i
      case $2
      when "edit","show"
        klass = $1.singularize.capitalize.constantize
        obj = klass.send("find_by_#{$5.singularize}", $4) if $4 && $5
        raise "could not find #{$3} #{$1}" unless obj
        return self.send("edit_#{$1.downcase.singularize}_path",obj) if $2 == "edit"
        return self.send("#{$1.singularize}_path",obj) if $2 == "show"
      when "new"
        self.send("new_#{$1.downcase.singularize}_path")
      when "overview"
        self.send("#{$1.downcase.pluralize}_path")
      end
    

    copy | embed

    0 comments - tagged in  posted by cbeier on Nov 18, 2009 at 3:22 a.m. EST
  • Simple ruby script to display info for a screenshot
    #!/usr/bin/env ruby
    
    ## Defining variables
    @color0 = "\e[0;36m"
    @color1 = "\e[0;32m"
    @ss = "scrot" ##program to capture screenshot (set to nil for no screenshot)
    @ssl = "~" ##location to save screenshot
    @kernel = `uname -r`
    @icon = `cat ~/.gtkrc-2.0 | grep gtk-icon-theme-name`.to_s.split("\"")[1]
    @theme = `cat ~/.gtkrc-2.0 | grep gtk-theme-name`.to_s.split("\"")[1]
    @font = `cat ~/.gtkrc-2.0 | grep gtk-font-name`.to_s.split("\"")[1]
    @tfont = `cat ~/.Xdefaults | grep font`.split("\n")[-1].split(":")[2]
    
    
    
    
    logo = "
    #{@color0}                       __       #{@color1}___                                 
    #{@color0}                      /\\ \\    #{@color1} /\\_ \\    __                          
    #{@color0}     __     _ __   ___\\ \\ \\___ #{@color1}\\//\\ \\  /\\_\\    ___   __  __  __  _  
    #{@color0}   /'__`\\  /\\`'__\\/'___\\ \\  _ `\\ #{@color1}\\ \\ \\ \\/\\ \\ /' _ `\\/\\ \\/\\ \\/\\ \\/'\\ 
    #{@color0}  /\\ \\L\\.\\_\\ \\ \\//\\ \\__/\\ \\ \\ \\ \\ #{@color1}\\_\\ \\_\\ \\ \\/\\ \\/\\ \\ \\ \\_\\ \\/>  </ 
    #{@color0}  \\ \\__/.\\_\\\\ \\_\\\\ \\____\\\\ \\_\\ \\_\\#{@color1}/\\____\\\\ \\_\\ \\_\\ \\_\\ \\____//\\_/\\_\\
    #{@color0}   \\/__/\\/_/ \\/_/ \\/____/ \\/_/\\/_/#{@color1}\\/____/ \\/_/\\/_/\\/_/\\/___/ \\//\\/_/
    \e[0m"
    puts logo
    puts
    
    puts "#{@color0}Kernel:\e[0m #{@kernel}"
    puts "#{@color0}Theme:\e[0m #{@theme}"
    puts "#{@color0}Icons:\e[0m #{@icon}"
    puts "#{@color0}Gtk Font:\e[0m #{@font}"
    puts "#{@color0}Terminal Font:\e[0m #{@tfont}"
    puts "#{@color0}Window Manager:\e[0m Xmonad"
    puts "\e[0m\n"
    
    `sleep 2;#{@ss} #{@ssl}/'%y-%m-%d_screenshot.png' -q 60`
    

    copy | embed

    0 comments - tagged in  posted by dangeroushobo on Nov 09, 2009 at 11:38 a.m. EST
  • 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'
    

    copy | embed

    0 comments - tagged in  posted by kevinvaldek on Nov 05, 2009 at 10:35 a.m. EST
  • TextUnbreak
    require 'rubygems'
    require 'profligacy/lel'
    require 'profligacy/swing'
    
    module TextUnbreak
      BREAK_DEFAULTS = ".?!"
      IGNORE_DEFAULTS = "'\"»)>}” "
    
      class UI
        include_package 'javax.swing'
        include_package 'java.awt'
        include Profligacy
    
        def initialize
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName)
          @font = Font.new("Dialog", Font::PLAIN, 12)
    
          layout = "
            [<input_label]
            [(500,150)input]
            [symbols]
            [detect_headings]
            [<output_label]
            [(500,150)output]
            [>buttons]"
          symbols_layout = "
            [<break_symbols_label|<ignore_symbols_label]
            [(250)break_symbols|(250)ignore_symbols]"
          buttons_layout = "[run|save]"
    
          @ui = Swing::LEL.new JFrame, layout do |c, i|
            c.input_label = JLabel.new "Input text:"
            @input = JTextArea.new
            @input.font = @font
            c.input = JScrollPane.new @input
            c.output_label = JLabel.new "Output text:"
            @output =  JTextArea.new
            @output.font = @font
            c.output = JScrollPane.new @output
    
            c.symbols = Swing::LEL.new(JPanel, symbols_layout) do |sc, si|
              sc.break_symbols_label = JLabel.new "Linebreak allowed on:"
              sc.ignore_symbols_label = JLabel.new "Ignore symbols:"
              @breaks = JTextField.new BREAK_DEFAULTS
              @ignores = JTextField.new IGNORE_DEFAULTS
              sc.break_symbols = @breaks
              sc.ignore_symbols = @ignores
            end.build :auto_create_container_gaps => false
    
            c.detect_headings = Swing::Build.new(JPanel,
                :preserve_headings, :length_field, :length_label) do |pc, pi|
              @preserve_headings = JCheckBox.new "Preserve headings: lines shorter than", true
              pc.preserve_headings = @preserve_headings
              @heading_length = JSpinner.new SpinnerNumberModel.new 64, 0, 256, 1
              pc.length_field = @heading_length
              pc.length_label = JLabel.new "characters"
            end.build do |container|
              container.layout = FlowLayout.new FlowLayout::LEFT
            end
    
            c.buttons = Swing::LEL.new(JPanel, buttons_layout) do |bc, bi|
              bc.run = JButton.new "Run"
              bc.save = JButton.new "Save"
              bi.run = { :action => method(:mend) }
              bi.save = { :action => method(:save) }
            end.build :auto_create_container_gaps => false
          end
    
          @ui.build(:args => "TextUnbreak").default_close_operation = JFrame::EXIT_ON_CLOSE
        end
    
        def mend (type, event)
          src = @input.text
          dest = ""
          src.split("\n").each { |line|
            if (!preserve?(line) && broken?(line))
              dest << line.strip << " "
            else
              dest << line.strip << "\n"
            end
          }
          @output.text = dest
          puts "sudo unbreak!"
        end
    
        def save (type, event)
          puts "hallelujah! another soul saved!"
        end
    
        def broken? (line)
          breaks = @breaks.text
          ignores = @ignores.text
          (line.length - 1).downto(0) do |i|
            char = line[i]
            if ignores.index(char) == nil
              return breaks.index(char) == nil
            end
          end
          false
        end
    
        def preserve? (line)
          @preserve_headings.selected && line.length <= @heading_length.value
        end
      end
    end
    
    SwingUtilities.invoke_later proc { TextUnbreak::UI.new }.to_runnable
    

    copy | embed

    0 comments - tagged in  posted by hvis on Oct 27, 2009 at 10:22 a.m. EDT
  • a simple example showing mixin in Ruby
    # animal.rb
    module Animal
      def walk
        puts 'walk'
      end
    end
    
    # dog.rb
    class Dog
      include Animal
    end
    
    # main.rb
    require 'animal'
    require 'dog'
    
    dog = Dog.new
    dog.walk
    

    copy | embed

    0 comments - tagged in  posted by jpartogi on Oct 20, 2009 at 9:35 a.m. EDT
  • To show the difference between instance variables and class variables in ruby
    class Point
      @@n = 0
    
      def initialize(x=0, y=0)
        @x, @y = x, y
        @@n += 1
      end
    
      def x
        @x
      end
    
      def x=(x)
        @x = x
      end
    
      def n
        @@n
      end
      
    end
    
    point1 = Point.new
    point1.x= 5
    puts point1.x
    
    point2 = Point.new
    point2.x = 6
    puts point2.x
    
    puts point1.n
    

    copy | embed

    0 comments - tagged in  posted by jpartogi on Oct 20, 2009 at 9:10 a.m. EDT
  • Signal handling
    Signal.trap("TERM") {puts "terminating..."; exit}
    

    copy | embed

    0 comments - tagged in  posted by mateuszzawisza on Oct 05, 2009 at 6:11 p.m. EDT
  • retry in rescue
    #example usage of retry in begin rescue clause
    #this retries 3 times then throws exception
    
    retries = 0
    begin
      smth_that_throws_exception
    rescue => e
      raise e if retries > 3
      retries += 1
      retry
    end
    

    copy | embed

    0 comments - tagged in  posted by mateuszzawisza on Sep 26, 2009 at 9:18 a.m. EDT
Sign up to create your own snipts, or login.