code
stringlengths
1
1.73M
language
stringclasses
1 value
module StringMy; def camelize string = ""; up = false; self.split("").each_with_index do |char, i| if char == "-"; up = true; elsif !up; string << char else; string << char.upcase up = false; end end string end end class String includ...
Ruby
def teste thread = Thread.new do puts "Rolling"; (1..5).each do |index| puts index; end end contdown = Thread.new do puts "."; end sleep(3); puts "Still Rolling?" thread.join puts "Not Anymore, I Know"; end teste
Ruby
class Carro attr_reader :marca, :modelo; def initialize(marca, modelo) @marca = marca || "Volkswagem"; @modelo = modelo || "Polo"; end def to_s return "#{@marca} - #{@modelo}"; end end class Garagem attr_reader :carros; def initialize(*carros) @carros = []; if carros carros.ea...
Ruby
class Automovel attr_reader :fabricante, :tipo; def initialize(fabricante, tipo) @fabricante = fabricante; @tipo = tipo; end def eu "Classe Automovel"; end end class Carro < Automovel alias :pai :eu; def initialize(fabricante) super fabricante, "Carro"; end def filho "Classe Carro q...
Ruby
class Carro attr_reader :marca, :modelo, :tanque; def initialize(marca, modelo, tanque) @marca = marca; @modelo = modelo; @tanque_capacidade = tanque; @tanque = tanque; end def enche_tanque(litros) @tanque = @tanque + litros; @tanque = @tanque_capacidade if @tanque > @tanque_capacidade; end ...
Ruby
require "bb_code" #----------------------------------------------------------------------------# location = 'D:\Developer\Workspaces\Admin\Bermonruf PHP\posts\MensagensDeErroEFormularios.html' #----------------------------------------------------------------------------# location = location.gsub('\\', '/')....
Ruby
class Object def random_name(length=(rand(10)+1)) Array.new(length){("a".."z").to_a.sort_by{rand}[0]}.join(""); end def local_variable_get(var, bind) eval(var, bind); end def local_variable_set(var, value, bind) locals = eval("local_variables", bind); begin tmp_var...
Ruby
module BBCode module REGEXP module MAKE def attrs(attrs) attr_regexp = ""; attrs.each do |name, value| _attr = attr(:attr_pair, :name => name, :value => value) + "\\s*"; attr_regexp << _attr; end Regexp.new(attr_regexp); ...
Ruby
require "ftools"; class Dir def self.each_entry(dir, &block) dir = dir.gsub("\\", "/").sub(/\/$/, ""); (entries(dir) - [".", ".."]).each do |entry| path = dir + "/" + entry; if File.directory?(path) each_entry(path, &block); else block.call(entry, dir); en...
Ruby
class Race attr_reader :name; def initialize(name) @name = name; end end class World attr_reader :name, :races; def initialize(name, &block) @name = name; @races = {}; instance_eval(&block) if block_given?; end protected def race(name) erace = Race.new(...
Ruby
class Object def in?(obj) raise NoMethodError, "cannot check if #{self.inspect} is in #{obj.inspect}" unless obj.respond_to?(:include?); obj.include?(self); end end class String def /(n) (split(" ") / n).map{|obj| obj.join(" ")}; end def -(str) gsub(str, ""); end ...
Ruby
class Module def once(*methods) methods.each do |method| method = method.to_sym; emethod = self.instance_method(method); self.send(:define_method, method) do |*args| @cached_methods ||= {}; unless @cached_methods[method] @cached_methods[method] = emethod.bin...
Ruby
require "open-uri" def list_dir(dir="./", opts={}, deep=0) text = "" marg = (opts[:margin] || " ") * deep Dir.chdir(dir) for entry in Dir.entries("./").delete_if{|a| [".", ".."].include?(a)} begin Dir.chdir entry Dir.chdir "../" text << (opts[:before_dirname] || "") text...
Ruby
require File.dirname(__FILE__) + "/serial.rb"; p Serial
Ruby
class SerialFormat GENERIC_SERIAL = /(?:\w+\s*-\s*)+\w+/ attr_reader :format, :regexp; def initialize(format=nil, *args) @format = format || GENERIC_SERIAL; @regexp = to_regexp(format, *args); end def test(serial) valid = serial =~ @regexp; valid = test_generic(serial) if gene...
Ruby
require File.dirname(__FILE__) + "/serial.rb"; require "net/http"; require "uri"; require "hpricot"; class SearchSerials def self.search(keywords, format=nil) keywords = keywords.join(" ") if keywords.kind_of?(Array); results = search_google "(serial|serials) #{keywords}" results = results.m...
Ruby
require "benchmark"; class Sort class << self def _prepare(array) (1..100).to_a.each{|n| n + 2;}; array.sort; end def rearray(array) array.inject([array.shift]) do |array, n| array.send((array.last >= n) ? :unshift : :push, n); array; en...
Ruby
class TestClass attr_accessor :car, :other; def initialize(car, other) @car = car; @other = other; puts (@car + @other) end def method_missing(method) puts("method_missing"+method.to_s()); end def car() puts "Hello World and Devel...
Ruby
class NerdText letters = ("A".."Z").to_a; Letters = (letters + letters.map{|s| s.downcase}).join(""); numbers = "43CD3F68lJK1MN0PQRS7UVWXY2"; Numbers = numbers + numbers.downcase; def self.translate(string) string.tr(Letters, Numbers); end end p(lambda{ NerdText.translate "...
Ruby
require "test/unit"; class Person attr_reader :name, :age, :friends; class WrongAgeError < Exception; end class DoubleFriendError < Exception; end class NoFriendError < Exception; end class FriendshipLevelExceeded < Exception; end MaximumFriendshipLevel = 5; def initialize(name, age) ...
Ruby
def debug(msg, first="a") sq = (first.."z").to_a; puts(msg); args = yield; args.each_with_index{|obj, i| print("#{sq[i]} = #{obj.inspect}; ");} puts "\n\n"; end a = "bird" b = "dog" c = "cat" d = ["bat", "pig"] def e; return "cow", "horse"; end def f; return ["duck", "fish"]; end def g; ["lion"...
Ruby
require 'demo_test_unit_extensions' class MetaprogrammingIntroduction < Test::Unit::TestCase =begin This is a demonstration of dynamic method definition using the private method Module#define_method and an introduction to singleton classes (also known as metaclasses). This is the basis of Ruby metaprogramming. Not...
Ruby
require 'test/unit' class Test::Unit::TestCase def self.show(name, &body) #~ name.gsub!(/\n/, '') #~ name.squeeze!(' ') #~ puts "* #{name} (Line #{line_from(caller.first)})" #~ define_method :"test #{name.gsub(/[[:punct:]]/,'')}", body puts name begin; body.call; rescue; end; end def...
Ruby
def invert(simbol) (simbol == "+" || simbol == false) ? "-" : "+"; end class Numeric def mod (self < 0) ? 0 - self : self; end end class Person attr_reader :name, :time_to_cross; attr_accessor :with_flashlight; def initialize(name, time_to_cross, with_flashlight=false) @name, @...
Ruby
a = "m" p local_variable_get("a")
Ruby
def validate_hash(hash, *required_opts) missed_opts = required_opts.reject{|opt| hash.key?(opt)} if missed_opts.size > 0 raise ArgumentError, "Your hash should have the keys #{missed_opts.join}" return false end true end class Car attr_reader :model, :factory, :gas_limit, :gas, :km_ru...
Ruby
module Chain class Proxy def method_missing(method, *args, &block) @result = (class << self; self; end).send(:define_method, method, &block); end def get @result; end end def chain(&block) chain = Proxy.new chain.instance_eval(&block); chain;...
Ruby
#If you don't have it yet, you'll need to install ruby-mp3info and rubyzip #libraries to play with MusicBank, to do that just go to the command line #and put "gem install ruby-mp3info" and "gem install rubyzip" if RubyGems is #ok and installed require "mp3info"; require "zip/zip"; require "builder"; require "tes...
Ruby
# If you don't have it yet, you'll need to install ruby-mp3info and rubyzip # libraries to play with MusicBank, to do that just go to the command line # and put "gem install ruby-mp3info" and "gem install rubyzip" if RubyGems is # ok and installed module Music end require "mp3info"; require "zip/zip"; require...
Ruby
module Music::Playlists private # Generates a WPL playlist, used inside the class. # def playlist_wpl(opts={}) #:doc: playlist = ""; xml = Builder::XmlMarkup.new(:target => playlist, :indent => (opts[:indent] || 4)); xml.instruct!("wpl", :version => "1.0"); xml.smil do xml.head...
Ruby
# TODO: Change the renaming system that is incremeanting numbers instead of renaming based on the deep of the copy's number class Music::Bank attr_reader :songs, :nosongs, :location; attr_accessor :finder_options, :rename_format, :run_play, :name; include Playlists; # Supported extensions for the m...
Ruby
class Music::Mp3Info # Method to return the time round in the "MM:SS" format. def time mins = length.to_i / 60; secs = length.to_i % 60; "%02d:%02d" % [mins, secs]; end end
Ruby
module Music class MusicError < StandardError; end class NoSongsInDirectoryError < MusicError; end end
Ruby
module Playlists private # Generates a WPL playlist, used inside the class. # def playlist_wpl(opts={}) #:doc: playlist = ""; xml = Builder::XmlMarkup.new(:target => playlist, :indent => (opts[:indent] || 4)); xml.instruct!("wpl", :version => "1.0"); xml.smil do xml.head do ...
Ruby
require "test/unit" class Test < Test::Unit::TestCase def initialize super end end
Ruby
def closures_in_loop_block(nclosures=5) closures = []; #Defining an Array that will hold the closures nclosures.times do |i| closures << lambda{"Actual: i = #{i}"}; end closures; end def closures_in_loop(nclosures=5) closures = []; #Defining an Array that will hold the closures i = 0; whil...
Ruby
require "net/http"; require "uri" def post(url, data) headers = { "User-Agent" => "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.1) Gecko/20060111 Firefox/2.0.0.9" }; url = URI.parse(url) res = Net::HTTP.new(url.host).start do |http| http.request_post(url.path, data, headers); en...
Ruby
%w(active_support mp3info).each{|f| require(f);}; class String def remove(*substs) substs.flatten.inject(self){|str, subst| str.gsub(subst, "");}; end alias_method :-, :remove; def sanitize self.downcase.chomp.remove(/\(.*?\)?/, /\s?(prod|feat|ft\.|featuring|remastered).*/).titleize.g...
Ruby
trata.simbols(:soma => "tanto", :isso =>"this")
Ruby
class Array def shuffle sort_by{rand}; end def pick_random self[rand(size)]; end end class Word attr_reader :word; class << self private def add_next_letters_for(letter, *nexts) next_letters = self.send(:class_variable_get, :@@next_letters); ...
Ruby
class Trata def trata(obj) return obj.test_if(false); end def simbols(simbols={}) puts ("soma="+simbols[:soma]+" isso="+simbols[:isso]); end end
Ruby
quiz = 199999995.99999 p quiz.to_s.reverse.gsub(/\d{3}/){|match| ($`.include?(".")) ? match + "," : match}.reverse.sub(/^,/, "") quiz = [1, [2, [3]]] p quiz.inject([]){|array, obj| (obj.kind_of?(Array)) ? array + obj : array << obj} quiz = ("a".."z").to_a p quiz.sort_by{rand} quiz = "File::Constants" p eva...
Ruby
class Regexp def self.build(*args) args = args.map{|n| n.to_a if n.kind_of?(Range)}.flatten.uniq; Regexp.new(args.join("|")) end end p(lambda{ if "zero 19" =~ Regexp.build(1..10) true else false end }.call)
Ruby
require "test/unit"; class Array def sum inject(0){|sum, n| sum + n;}; end end class ChangeError < StandardError; end def make_change(amount, coins=[25, 10, 5, 1]) change = coins.sort.reverse.inject([]) do |change, coin| change << coin until change.sum + coin > amount; change; ...
Ruby
class Module def square_brackets(*methods) methods.each do |method| method = method.to_s; emethod = self.instance_method(method); self.send(:define_method, method) do |*args| emethod.bind(self) end end end end class Person def walk(name) put...
Ruby
class Part attr_reader :atom; def initialize(atom) @atom = atom; end end class Eletron < Part attr_reader :layer; Levels = {:s => 1, :p => 2, :d => 3, :f => 4}; def initialize(atom, layer, level) super(atom); @layer = layer; self.level = level end def level=...
Ruby
def media(*args) args.inject(0){|s, n| s + n} / args.size.to_f end p(lambda{ media 5, 10 }.call)
Ruby
class NiceRuby def self.watch(&block) puts self.new.instance_eval(&block); end def method_missing(word, *args) str = word.to_s + " " + args.join(" "); str << yield if block_given?; this_method = self.method(:method_missing).to_proc; (class << str; self; end).send(:define_method, :m...
Ruby
require "tests/console/console"; class SchoolConsole < Console Student = Struct.new(:id, :name, :age); Classroom = Struct.new(:id, :name, :students); students_id = 0; classrooms_id = 0; index "1: Inserir Aluno", "2: Inserir Classe", "3: Listar Alunos", "4: Listar Classes", ...
Ruby
class Console @@index = ""; @@before_filters = []; @@after_filters = []; OptionMethod = "option_%s"; class NoCommandError < StandardError; end class NoFilterError < StandardError; end class << self alias_method :start, :new; protected def page_separator(se...
Ruby
require "rexml/document" require "net/http" require "uri" languages = { "asp" => "ASP", "actionscript" => "ActionScript", "apache" => "Apache Log", "applescript" => "AppleScript", "bash" => "Bash", "c_mac" => "C", "c" => "C", "csharp" => "C#", "cpp-qt" => "C++", "cpp" => "C++", "ca...
Ruby
class Dir def self.exists?(dir) begin Dir.chdir(dir); Dir.chdir("../"); return true; rescue return false end end def self.dir?(*args) self.exists?(*args) end def self.create(dir, move=true) unless self.exists?(dir) self.mkdir(dir) ...
Ruby
class Array def *(n) Array.new(n, self) end end def allpossibles(algs, combinable=false) letters = combinable || ("a".."z").to_a; words = []; code = ""; concat = "words <<" algs.times do |col| code << "letters.each do |a#{col}|\n" concat << " a#{col} + " end code = code + ...
Ruby
require "erb"; class PHPController attr_accessor :attributes, :model_name, :table_name; def initialize(opts) opts.each do |var, value| instance_variable_set("@#{var}", value); end end def make_code code = File.open("tests/php_create/controller.php.erb"){|f| f.read;}; co...
Ruby
require "erb"; class PHPModel attr_accessor :attributes, :model_name, :table_name; def initialize(opts) @attributes = opts[:attributes]; @model_name, @table_name, @plural = opts[:model_name], opts[:table_name], opts[:plural]; @created_at = opts[:created_at]; end def make_code ...
Ruby
Data = { :episodes => { :next_ruby => [:ruby], :confusion => [:tech, :ruby], :may_news => [:magazine], :april_news => [:famous, :hollywood], :august_news => [:hollywood, :magazine] },:podcasts => { :ruby => [:ruby, :tech], :daily => [:hollywood, :famous] } }; def print_fi...
Ruby
require "test/unit" class Class def method_missing(method, *args, &block) if method.to_s =~ /(attr_.+)_with_defaults/ attr_defaults(args.first, $1); else super(method, *args, &block); end end def attr_defaults(attrs, method=:attr_accessor) self.send(method, *attrs.k...
Ruby
class Enquete attr_reader :options; def initialize(*args) @options = {}; @max_str = 0; meta = (class << self; self; end); args.each do |arg| arg = arg.to_sym; @options[arg] = 0; meta.send(:define_method, arg) {@options[arg]}; @max_str = arg.to_s.length + 4 if ar...
Ruby
class Carro attr_reader :marca, :modelo, :cor; @teste = "tested"; def initialize(marca, modelo, cor) @marca = marca; @modelo = modelo; @cor = cor; end def teste? @teste; end def self.teste @teste; end def to_s return "[Carro marca:#{@marca} modelo:#{@modelo}]"; end end
Ruby
class Montadora attr_reader :marca; @@carros = 0; def initialize(marca) @marca = marca; end def monta_carro(modelo, cor) carro = Carro::new(@marca, modelo, cor); @@carros += 1; return carro; end def self.carros return @@carros; end end
Ruby
def requires(*files) files.each {|file| require file;} end requires "carro", "montadora"; #Constante = "Tirnta" #class Carro # def test # "tested and passed" # end #end #class Carro # remove_method :test; #end volks = Montadora::new("Volks"); golf = volks.monta_carro("Golf", :azul) puts Montadora::ca...
Ruby
# See "An Approach to Composing Domain-Specific Languages in Ruby": # http://weblog.raganwald.com/2007/03/approach-to-composing-domain-specific.html # # Created by Reginald Braithwaite on 2007-03-11. # Copyright (c) 2007. All rights reserved. # # DO WHAT THE FUCK YOU WANT TO PUBLIC LICE...
Ruby
class Url attr_reader :parts; def initialize @parts = []; end def self.parse(&block) url = new url.instance_eval(&block); url; end def to_s @parts.join(".").gsub("./.", "/"); end private def method_missing(part, *args) p [part, @parts] @parts...
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/server'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/breakpointer'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/about'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/plugin'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/breakpointer'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/destroy'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/generate'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/runner'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/console'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/server'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/runner'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/plugin'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/about'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/boot' require 'commands/performance/benchmarker'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/boot' require 'commands/performance/profiler'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/boot' require 'commands/performance/benchmarker'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/boot' require 'commands/performance/profiler'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/boot' require 'commands/process/inspector'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/boot' require 'commands/process/reaper'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/boot' require 'commands/process/spawner'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/boot' require 'commands/process/spawner'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/boot' require 'commands/process/reaper'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../../config/boot' require 'commands/process/inspector'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/destroy'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/console'
Ruby
#!/usr/bin/env ruby require File.dirname(__FILE__) + '/../config/boot' require 'commands/generate'
Ruby
class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.column :fullname, :string; t.column :username, :string; t.column :password, :string; t.column :email, :string; t.column :created_at, :datetime; end end def self.down drop_table :users ...
Ruby
class CreateNotes < ActiveRecord::Migration def self.up create_table :notes do |t| t.column :project_id, :integer; t.column :user_id, :integer; t.column :title, :string; t.column :body, :text; t.column :created_at, :datetime; end end def self.down drop_table :notes end...
Ruby
class CreateProjects < ActiveRecord::Migration def self.up create_table :projects do |t| t.column :user_id, :integer; t.column :title, :string; t.column :description, :text; t.column :created_at, :datetime; end end def self.down drop_table :projects end end
Ruby
class CreateAttachments < ActiveRecord::Migration def self.up create_table :attachments do |t| t.column :name, :string; t.column :mime_type, :string; t.column :public, :boolean, :default => 1; t.column :storable_id, :integer; t.column :storable_type, :string; t.column :created_...
Ruby
class CreateImagesDocuments < ActiveRecord::Migration def self.up add_column :attachments, :type, :string; end def self.down remove_column :attachments, :type; end end
Ruby
# Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require(File.join(File.dirname(__FILE__), 'config', 'boot')) require 'rake' require 'rake/testtask' require 'rake/rdoctask' require 'tasks/rails'
Ruby
class Document < Attachment #validates_inclusion_of :mime_type, :in => ["jpeg", "jpg", "gif", "png", "pdf", "doc"]; def editable?(user) (storable.kind_of?(Note) && storable.project.user?(user)) ? true : user?(user); end end
Ruby
module UsersHelper def projects(user) projects = (user.kind_of?(User)) ? user.projects : user; projects = projects.map do |project| link_to(project.title, project_path(:id => project.id, :name => project.name)); end (projects.empty?) ? "Nenhum" : projects.to_sentence(:connector => "e"); end ...
Ruby
module ProjectsHelper def text_if_referer(first, second, includes) referer = @request.env["HTTP_REFERER"] (referer && referer.include?(includes)) ? second : first; end def notes(project) notes = project.notes.count; msg = case notes when 0 "nenhuma nota"; when 1 "uma...
Ruby
module LoginHelper end
Ruby
module NotesHelper end
Ruby