Public
snipts » ruby
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
-
∞ 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
-
∞ module_function
module Math def sin(x) # ... end module_function :sin end Math.sin(1) include Math sin(2)
-
∞ 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}" # . . .
-
∞ 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
-
∞ 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
-
∞ 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
-
∞ Prepends " - " to each line
ruby -n -e 'puts " - " + $_' bla.txt -
∞ 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
-
∞ 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}"
-
∞ 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
-
∞ 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
-
∞ 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
-
∞ 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`
-
∞ 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'
-
∞ 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
-
∞ 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
-
∞ 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
-
∞ Signal handling
Signal.trap("TERM") {puts "terminating..."; exit}
-
∞ 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



Python in a Nutshell, Second Edition