Code Language: ruby

Easy array to hash in Ruby

Language: Ruby

Hash[*User.all.collect{|u|[u.id,u.email]}.flatten]

# {1=>"foo@gmail.com", 2=>"bar@gmail.com", 3=>"baz@inmunited.com"}
Reveal More
Added 8 months ago by 2699425249_32de9cf0fc_o_normal codemariner

Simple Password Generator

Language: Ruby

#!/usr/bin/env ruby
require 'net/http'
begin
  require 'clipboard'
rescue LoadError
end
len = ARGV[0] || 15
response = Net::HTTP.get URI.parse("http://www.random.org/strings/?num=1&len=#{len}&digits=on&upperalpha=on&loweralpha=on&unique=on&format=plain&rnd=new")
Clipboard.copy response if Clipboard
puts response
Reveal More
Added 11 months ago by Glider_normal linopolus

class methods are singleton methods of a class object

Language: Ruby

class Car
  def initialize(name)
    @name = name
  end
end

class << Car
  def create_a_car
    self.new(:name => "Porsche")
  end
end

my_new_car = Car.create_a_car
Reveal More
Added 11 months ago by Shaved_normal luckydev

Proper backtrace with eval'd heredoc in Ruby

Language: Ruby

module MyModule
  module ClassMethods
    def string(name)
      module_eval <<-RUBY , __FILE__, __LINE__ + 1
        def #{name}
          raise "#{name}" #line number 6
        end
      RUBY
    end
  end

  def self.included(base)
    base.extend(ClassMethods)
  end
end


class MyClass
    include MyModule

    string :foo
end

m = MyClass.new
m.foo

# results in
# $ ruby ./test.rb 
#./test.rb:6:in `foo': foo (RuntimeError)
#	from ./test.rb:25
Reveal More
Added 12 months ago by 2699425249_32de9cf0fc_o_normal codemariner

SSH port forwarding with Ruby

Language: Ruby

#!/usr/bin/env ruby

require 'rubygems'
require 'net/ssh'

hosts = {:diginode2 => {:host => "64.93.11.111", :forwarding => [
                          {:local_port => 3002, :local_host => "localhost", :remote_port => 3000}, # admin webapp
                          {:local_port => 1936, :local_host => "localhost", :remote_port => 1935}, # fms rtmp
                          {:local_port => 1112, :local_host => "localhost", :remote_port => 1111} # fms admin
                         ]
         },
         :diginode1 => {:host => "64.93.11.112", :forwarding => [
                          {:local_port => 3000, :local_host => "192.168.19.50", :remote_port => 3000}, # admin app
                          {:local_port => 3001, :local_host => "localhost", :remote_port => 3001}, # admin app
                          {:local_port => 1935, :local_host => "localhost", :remote_port => 1935}, # fms rtmp
                          {:local_port => 1111, :local_host => "localhost", :remote_port => 1111} # fms admin
                         ]
         },
         :diginode3 => {:host => "64.93.11.113", :forwarding => [
                          {:local_port => 1937, :local_host => "localhost", :remote_port => 1935}, # fms rtmp
                          {:local_port => 1113, :local_host => "localhost", :remote_port => 1111} # fms admin
                         ]
         },
         :record1 => {:host => "64.93.11.211", :forwarding => [
                          {:local_port => 9001, :local_host => "localhost", :remote_port => 8000} # json rpc
                         ]
         },
         :record2 => {:host => "64.93.11.212", :forwarding => [
                          {:local_port => 9002, :local_host => "localhost", :remote_port => 8000} # json rpc
                         ]
         },
         :record14 => {:host => "64.93.11.224", :forwarding => [
                          {:local_port => 9014, :local_host => "localhost", :remote_port => 8000} # json rpc                                                                                                  
                         ]
        }
}




hosts.each do |name, config|
  Thread.new {
    puts "connecting to #{config[:host]}"
    Net::SSH.start(config[:host], "diginode", :password => "fc8arca#0ne") do |ssh|
      forwards = config[:forwarding]
      forwards.each do |f|
        puts "forwarding #{f[:local_port]}, #{f[:local_host]}, #{f[:remote_port]} from #{config[:host]}"
        ssh.forward.local(f[:local_port], f[:local_host], f[:remote_port])
      end
      ssh.loop {true}
    end
  }
end


while (true)
  sleep(0.5)
end 
Reveal More
Added 12 months ago by 2699425249_32de9cf0fc_o_normal codemariner

Rake task exception handler with Binding play

Language: Ruby

# something that represents a rake task                                                                          
class Task
  attr_accessor :name                                                                                                 
  def initialize(name)                                                                                                
    @name = name                                                                                                      
  end
end 
  
                                                                                                                      
# something like a rake 'task' method
def task(name, &block)
  yield Task.new(name)
end     
        
      
# a method that will execute a block defined inside of a rake task
# the idea is that this method can trap and report on exceptions
# I want to get the task name to include in the report in as transparent
# of a way as possible.  Unfortunately, it seems eval is the only way to
# go about getting this.
def handler(&block)
  begin
    yield
  rescue Exception => e
    # ideally, this would test for t first
    name = block.binding.eval('t.name')
    puts "error in task '#{name}': e.message"
  end
end


task "publish" do |t|
  handler do
    # stuff here
    # handler will pick up t
    raise "something bad happened"
  end
end


# this results in
#   error in task 'publish': e.message
Reveal More
Added 12 months ago by 2699425249_32de9cf0fc_o_normal codemariner

Builder-like configuration approach to set class variables on a config class.

Language: Ruby

module Stalky                                                                 
  # config object that will be globally accessible                                                                                                          
  # as Stalky::Config
  class Config
    # same ol attr_accessor but applied to the Config class itself
    class << self; attr_accessor :qwerly_api_key, :rapleaf_api_key; end

    def initialize(&block)
      # pass the Config class into the given block
      yield Config if block_given?
    end
  end
end


# put this in something like config/initializers/stalky.rb
Stalky::Config.new do |config|
  config.qwerly_api_key = "foo"
  config.rapleaf_api_key = "bar"
end


# displays 'foo'
puts Stalky::Config.qwerly_api_key
# displays 'bar'
puts Stalky::Config.rapleaf_api_key
Reveal More
Added about 1 year ago by 2699425249_32de9cf0fc_o_normal codemariner

Re: Load yml configuration to a constant.

Refactoring of: Load yml configuration to a constant.

Language: Ruby

# stick this in some kind of initializer code like config/environment.rb
APP_CONFIG = YAML.load_file("#{Rails.root}/config/app_config.yml")

# to make it environment specific
APP_CONFIG = YAML.load_file("#{Rails.root}/config/app_config.yml")[Rails.env]

# sample yaml :
<<-YAML # put this in config/app_config.yml

development:
  api_key: abcdefg

production:
  api_key: 1234567

YAML


# then you can access like this:
api_key = APP_CONFIG['api_key']
Reveal More
Added about 1 year ago by 2699425249_32de9cf0fc_o_normal codemariner

Load yml configuration to a constant.

Language: Ruby

# stick this in some kind of initializer code like config/environment.rb
APP_CONFIG = YAML.load_file("#{Rails.root}/config/app_config.yml")

# to make it environment specific
APP_CONFIG = YAML.load_file("#{Rails.root}/config/app_config.yml")[Rails.env]

# sample yaml :
<<-YAML # put this in config/app_config.yml

development:
  api_key: abcdefg

production:
  api_key: 1234567

YAML

# then you can access like this:
api_key = APP_CONFIG['api_key']
Reveal More
Added about 1 year ago by 2699425249_32de9cf0fc_o_normal codemariner

Class method memoization in Rails

Language: Ruby

class Foo
  def self.do_it
    "bar"
  end
  class << self; extend ActiveSupport::Memoizable; self; end.memoize :do_it
end
Reveal More
Added about 1 year ago by 2699425249_32de9cf0fc_o_normal codemariner

Truncate string while respecting word boundaries

Language: Ruby

# truncates a string based on word boundaries rather than
# actual length
def truncate_words(text, num_words = 30, end_string = '...')
  return unless text
  words = text.split()
  words[0..(num_words-1)].join(' ') + (words.size > num_words ? end_string : '')
end
Reveal More
Added about 1 year ago by 2699425249_32de9cf0fc_o_normal codemariner

Use mongrel to easily serve files in your current directory

Language: Ruby

require 'rubygems'
require 'mongrel'

server = Mongrel::HttpServer.new("0.0.0.0", "8888")
server.register("/", Mongrel::DirHandler.new("."))
server.run.join
Reveal More
Added about 1 year ago by 2699425249_32de9cf0fc_o_normal codemariner

Send request to a server with both post and get data

Language: Ruby

def ask_server(post_data, get_data)
  require "net/http"
  require "uri"

  uri = URI.parse("http://www.example.org")
  http = Net::HTTP.new(uri.host, uri.port)
  get_params = '?get_key=' + get_data
  request = Net::HTTP::Post.new(uri.request_uri + get_params)
  request.set_form_data(post_data)
  response = http.request(request)
end
Reveal More
Added over 1 year ago by Weirdfish_upic_normal ilzoff

Load CouchDB logs

Language: Ruby

#!/usr/bin/env ruby -rubygems
require 'couchrest'
require 'time'

abort "usage: #{$0} DB_URL INPUT_FILE_PATH" unless ARGV.length == 2

DB_URL = ARGV[0]
INPUT_FILE_PATH = ARGV[1]
BULK_SAVE_LIMIT = 5000
LOG_LINE_REGEXP = /^\[([^\]]+)\] \[([^\]]+)\] \[([^\]]+)\] ([\d.]+) - - '(\S+)' (\S+) (\d+)\s*$/

def parse_line line
  match = LOG_LINE_REGEXP.match(line)
  return {
    :time => Time.parse(match[1]).utc.iso8601,
    :type => match[2],
    :erlang_pid => match[3],
    :ip_address => match[4],
    :verb => match[5],
    :url => match[6],
    :response_code => match[7].to_i
  } unless match.nil?
end

db = CouchRest.database! DB_URL
db.bulk_save_cache_limit = BULK_SAVE_LIMIT

open(INPUT_FILE_PATH).each_line do |line|
  doc = parse_line line
  unless doc.nil?
    db.save_doc doc, true 
    putc '.'
  end
end
db.bulk_save
puts 'done'
Reveal More
Added over 1 year ago by Segal-avatar_normal zdzolton

Sum of even numbers in range (One liner)

Language: Ruby

puts Range.new(0,100).to_a.find_all{ |i| i.to_i%2==0}.inject(0){ |sum,i| sum+i}
Reveal More
Added over 1 year ago by What_normal otobrglez

Quick and dirty memory profiling

Language: Ruby

require 'pp'

def print_class_counts
  c = Hash.new 0
    ObjectSpace.each_object(Object) do |o|
    c[o.class] += 1
  end
  pp c.sort_by{|k,v|v}.reverse
end
Reveal More
Added almost 2 years ago by Costco_normal trevorturk

Using Redis for configuration management

Language: Ruby

# Origin: https://gist.github.com/4de7b3c1522b155008e1

module GitHub
  module Config
    def self.[](key)
      $redis.get("gh:cfg:#{key}")
    end

    def self.[]=(key, value)
      $redis.set("gh:cfg:#{key}", value)
    end
  end
end
Reveal More
Added almost 2 years ago by Twitterprofilephoto_normal zh

Integrate WebSockets (via sunshowers) in Sinatra application

Language: Ruby

# create config.ru like:
#
#   require 'echowebsocket'
#   run EchoWebSocket.new
#
# and start it with: 
#
#   rackup config.ru -s thin -E production -p 8000
#
# echowebsocket.rb will be:

require 'sinatra'
require 'sunshowers'

class Sinatra::Request < Rack::Request
  include Sunshowers::WebSocket
end

class EchoWebSocket < Sinatra::Base
  set :sessions, true

  get "/echo" do
    if request.ws?
      request.ws_handshake!

      request.ws_io.each do |record|
        ws_io.write_utf8(record)
        break if record == "Goodbye"
      end

      begin
        request.ws_quit!
      rescue
        nil
      end
    end
    "You're not using Web Sockets"
  end
end
Reveal More
Added almost 2 years ago by Twitterprofilephoto_normal zh