RubySnips

From Custard
Jump to: navigation, search

Contents

Ruby Snippets

Her

require 'her'

Her::API.setup url: "http://pomegranate.ltd.uk" do |c|
  c.use Faraday::Request::UrlEncoded
  c.use Her::Middleware::DefaultParseJSON
  c.use Faraday::Adapter::NetHttp
end

# => #<Her::API:0x007ffd7888a130 @base_uri="http://pomegranate.ltd.uk", @options={:url=>"http://pomegranate.ltd.uk"}, @connection=#<Faraday::Connection:0x007ffd79006f30 @parallel_manager=nil, @headers={"User-Agent"=>"Faraday v0.9.0"}, @params={}, @options=#<Faraday::RequestOptions (empty)>, @ssl=#<Faraday::SSLOptions (empty)>, @default_parallel_manager=nil, @builder=#<Faraday::RackBuilder:0x007ffd7900af68 @handlers=[Faraday::Request::UrlEncoded, Her::Middleware::FirstLevelParseJSON, Faraday::Adapter::NetHttp]>, @url_prefix=#<URI::HTTP:0x007ffd79009fc8 URL:http://pomegranate.ltd.uk/>, @proxy=nil>>

class Poop
include Her::Model
end

Poop
Poop.all

# => #<Her::Model::Relation:0x007ffd7ac2ac98 @parent=Poop, @params={}, @_fetch=nil>

Poltergeist/PhantomJS/Capybara Cucumber config

features/support/env.rb

require 'capybara'
require 'capybara/rspec'
require 'capybara/dsl'
require 'capybara/cucumber'
require 'capybara/poltergeist'

# Poltergeist / PhantomJS
Capybara.javascript_driver = :poltergeist
Capybara.register_driver :poltergeist do |app|
  options = {
    timeout: 60,
    js_errors: true,
    inspector: true,
    phantomjs_options: ['--load-images=no','--ssl-protocol=any']
  }
  Capybara::Poltergeist::Driver.new(app, options)
end
Capybara.default_driver = :poltergeist
Capybara.run_server = false

Benchmark

require 'benchmark'

n = 50000
Benchmark.bm(7) do |x|
  x.report("for:")   { for i in 1..n; a = "1"; end }
  x.report("times:") { n.times do   ; a = "1"; end }
  x.report("upto:")  { 1.upto(n) do ; a = "1"; end }
end

Unicorn

Web server for sinatra or rails apps.

  • sudo apt-get install postgresql-server-dev-8.4 postgresql (if using postgres)
  • gem install unicorn
  • unicorn OR unicorn_rails

ServerSpec

RSpec tests for your servers configured by Puppet etc.

libusb

Capybara DSL

  • visit( '/my_url' )
  • current_pat.should == '/my_url'
  • click_link( 'link_id' ) # or Link Text
  • click_button( 'Submit' )
  • click_on( 'Link Text' )
  • fill_in( 'Username', :with => 'Custard' )
  • choose( 'Radio Button' )
  • check( 'Checkbox' )
  • uncheck( 'Checkbox' )
  • attach_file( 'Image', '/path_to/image.png' )
  • select( 'Option', :from => 'SelectBox' )
  • page.has_selector?('table tr')
  • page.has_selector?(:xpath, '//table/tr')
  • page.has_xpath?('//table/tr')
  • page.has_css?('table tr.foo')
  • page.has_content?('foo')
  • page.has_no_xpath?('a')
  • page.should have_selector('table tr')
  • page.should have_selector(:xpath, '//table/tr')
  • page.should have_xpath('//table/tr')
  • page.should have_css('table tr.foo')
  • page.should have_content('foo')
  • page.should_not have_xpath('a')
  • page.should have_no_xpath('a')
  • find_link('Hello').visible?
  • find_field('First Name').value
  • find_button('Send').click
  • find(:xpath, "//table/tr").click
  • find("#overlay").find("h1").click
  • all('a').each { |a| a[:href] }
  • within("li#employee") do
  • within(:xpath, "//li[@id='employee']") do
  • within_fieldset('Employee') do
  • within_table('Employee') do
  • page.execute_script("$('body').empty()")
  • result = page.evaluate_script('4 + 4');
  • save_and_open_page
  • print page.html
  • page.save_screenshot('screenshot.png')
  • Capybara.exact = true # Change matching to exact matching.
  • Capybara.match = :first | :one | :smart | :prefer_exact
  • Capybara.default_wait_time = 5
  • Capybara.current_driver = :selenium
  • Capybara.app_host = 'http://www.google.com'
  • session = Capybara::Session.new(:webkit, my_rack_app)

Listing Amazon EC2 instances in Rails Model

# Class for VM's 
class Vm
  include ActiveModel::Validations

  validates_presence_of :name, :status

  attr_accessor :id, :name, :dns, :status
  @@ec2 = AWS::EC2.new()

  def self.all
    return @@ec2.instances.inject([]) { |m, i|
      tags = i.tags.to_h
      name = tags['Name']
      m.push Vm.new( i.id, name, i.dns_name, i.status )
    }
  end

  def initialize( id, name, dns,  status )
    @id     = id
    @name   = name
    @dns    = dns
    @status = status
  end

end

Listing Amazon S3 buckets in Rails Model

# Class for S3 Storage
class Storage
include ActiveModel::Validations
 
validates_presence_of :name
 
attr_accessor :name
@@ec2 = AWS::S3.new()
 
def self.all
return @@ec2.buckets.inject([]) { |m, i|
    m.push Storage.new( i.name )
}
end
 
def initialize( name )
@name = name
end
 
end

AWS Config in Rails

config/initializers/aws-sdk.rb

AWS.config({
  :secret_access_key => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
  :access_key_id => 'YYYYYYYYYYYYYYY',
  :region => 'us-west-2',
})

Cucumber

Install Cucumber for BDD using rvm

  • rvm install 1.9.3
  • rvm use 1.9.3
  • gem install cucumber
  • gem install rspec

Cucumber in Rails


Quick Trick Sinatra Server

With a snip for displaying the request headers

#!/usr/bin/ruby
require 'rubygems'
require 'sinatra'

helpers do
  def request_headers
    env.inject({}){|acc, (k,v)| acc[$1.downcase] = v if k =~ /^http_(.*)/i; acc}
  end  
end


get '/' do
  puts request_headers.inspect
end

Inject

http://blog.jayfields.com/2008/03/ruby-inject.html

Loops

  • (1..10).each { |i| puts i }
  • 10.times {|i| p i+1}
  • 1.upto(10) { |i| puts i }
  • for i in 1..10; puts i; end

yield

#!/usr/bin/ruby

class Loopy
    def loop( count=1 )
        1.upto(count) do |i|
            yield i
        end
    end
end

loopy = Loopy.new()

loopy.loop(5) do |i|
    puts i
end

Finding paths relative to gem lib file

Assuming a method in a class in proj/lib and templates in proj/templates

    def template_path_for(template_id)
      File.expand_path( File.join( File.dirname(__FILE__), "../templates", "#{template_id}.erb"))
    end

Make your own Gem

Create gemspec

% cat slothsay.gemspec
Gem::Specification.new do |s|
  s.name        = 'slothsay'
  s.license     = 'MIT'
  s.version     = '0.0.1'
  s.date        = '2014-03-25'
  s.summary     = "Slothsay"
  s.description = "Slothsay: slothsay hello"
  s.authors     = ["custard"]
  s.email       = 'custard@cpan.org'
  s.bindir      = 'bin'
  s.executables << 'slothsay'
  s.files       = [
    "bin/slothsay",
    "lib/cat.rb",
    "lib/catsay.rb",
    "lib/exceptions.rb",
    "cats/default.erb",
    "cats/test.erb"
  ]
  s.homepage    = 'https://github.com/CustardCat/slothsay'
end

Variant:

  gem.files         = `git ls-files`.split($\)
  gem.executables   = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
  gem.test_files    = gem.files.grep(%r{^(test|spec|features)/})

Create the gem

gem build mygem.gemspec

Publish on RubyGems.org

Authenticate:

curl -u Custard https://rubygems.org/api/v1/api_key.yaml

This will create a ~/.gem/credential file in your home directory.

Push your gem to RubyGems.org

gem push mygem-0.0.1.gem


Installing Ruby Gems.

Get the source http://rubyforge.org/frs/download.php/45905/rubygems-1.3.1.tgz (http://rubyforge.org/projects/rubygems/)

Unpack...

cd /tmp
gunzip rubygems-1.3.1.tgz
tar -xvf rubygems-1.3.1.tar

Install...

cd rubygems-1.3.1
ruby setup.rb

Install Rails.

Use Gem. Make sure gems are updated first, then use gem to install Rails.

gem update
gem install rails

Running Rails under FastCGI

Apache:Unix

You need to install fastcgi, and the mod_fcgi module for apache

Install fcgi

wget http://www.fastcgi.com/dist/fcgi-2.4.0.tar.gz
{| border="1"
|-
gzcat fcgi-2.4.0.tar.gz || tar -xvf -
|}

cd fcgi-2.4.0
./configure
make
make install

Install mod_fastcgi

wget http://www.fastcgi.com/dist/mod_fastcgi-2.4.2.tar.gz
{| border="1"
|-
gzcat /mod_fastcgi-2.4.2.tar.gz || tar -xvf -
|}

cd /mod_fastcgi-2.4.2
cp Makefile.AP2 Makefile
vi Makefile		# Edit the Apache location
make
make install
			
Install ruby fcgi
gem install fcgi

Configure Apache httpd.conf Add the following...

LoadModule fastcgi_module     modules/mod_fastcgi.so

        FastCgiIpcDir /tmp/fcgi_ipc/
        AddHandler fastcgi-script .fcgi
        FastCgiServer /path/to/your/rails/app/public/dispatch.fcgi -idle-timeout 120 -initial-env RAILS_ENV=production -processes 2

Getting MySql working with Rails.

Solaris 10

Ruby needs to have the mysql adapter installed in order to access the mysql database. This adapter uses libmysqlclient.so.

Install ruby mysql
gem install mysql

If you get errors for 'ginstall not found' install the GNU fileutils package from SunFreeware. I Also had to link /usr/local/bin/install to /usr/local/bin/ginstall

wget ftp://mirror.sprintlink.net/sunfreeware.com/pub/freeware/sparc/9/fileutils-4.1-sol9-sparc-local.gz
gunzip fileutils-4.1-sol9-sparc-local.gz
pkgadd -d fileutils-4.1-sol9-sparc-local
cd /usr/local/bin
ln -s install ginstall	# If ginstall not present

If you get messages saying 'checking for mysql_query() in -lmysqlclient... no' You may need to add the path to where the libmysqlclient.so file is kept.

LD_LIBRARY_PATH=/usr/local/lib:/usr/sfw/lib
export LD_LIBRARY_PATH

Then retry the installation.

A simple Rails app

  • rails new my_spangly_project
  • rails generate
  • rails generate scaffold Cable name:string location:string
  • rails generate scaffold Person name:string location:string email:string
  • rails generate scaffold CableAllocation references:cable_id references:person_id start:date expiry:date
  • rake db:migrate
  • rails server


Complex

I was mucking about with the Complex class one day and found some code on the internet that generated Mandelbrot figures..

#!/usr/bin/ruby
#
# program: complex
# purpose: experiment with ruby complex number classes.
#
require 'complex'

class Main
        def initialize(bailout=50, iterations=100)
                @bailout, @iterations = bailout, iterations
        end

        def mandelbrot(x, y)
                c = Complex(x, y)
                z = 0
                @iterations.times do |i|
                        z = z**2 + c                       # This is the Mandelbrot operation.
                        return false if z > @bailout
                end
                return true
        end

        def render(x_size=80, y_size=24, inside_set="*", outside_set=" ")
                0.upto(y_size) do |y|
                        0.upto(x_size) do |x|
                                scaled_x = -2 + (3 * x / x_size.to_f)
                                scaled_y = 1 + (-2 * y / y_size.to_f)
                                print mandelbrot(scaled_x, scaled_y) ? inside_set : outside_set
                        end
                        puts
                end
        end

        def add
                puts "Add..."
                c = Complex.new( 0,1 )
                puts c.inspect
                puts c.conjugate.inspect
                puts c.inspect
                puts c.polar.inspect
        end
end

main = Main.new
main.render(120,50)

XMPP

#!/usr/bin/ruby

require 'rubygems' 
require 'xmpp4r/client' 
require 'xmpp4r/roster' 
require 'xmpp4r/muc' 
include Jabber

#Jabber::debug = true 
jid = JID::new( 'a.user@gmail.com/home' ) 
xmpp = Client::new( jid ) 
xmpp.connect 
xmpp.auth( 'APassword' ) 
puts "set_type :available"
xmpp.send(Presence.new.set_type(:available))

roster = Roster::Helper.new( xmpp ) 
roster.add_subscription_request_callback do |item,pres| 
  roster.accept_subscription( pres.from ) 
end

# subscribe
xmpp.send(Presence.new.set_type(:subscribe).set_to("a.user@gmail.com"))

#muc sttuff - multi user conferences
#mucjid = JID::new( 'groupname@some.jabber.server/group' ) 
#muc = MUC::MUCClient.new( xmpp ) 
#muc.join( mucjid )

#xmpp.add_update_callback do |m| 
#  puts m.inspect 
#end

xmpp.add_message_callback do |m| 
  puts m.inspect 
	msg = Message.new( "a.user@gmail.com", "I see your "+m.body )
	msg.type=:chat
	xmpp.send( msg )
end


while 1 do 
  sleep 1 
end

Binary Search

test_binary

#!/usr/bin/ruby

require 'binary.rb'
require 'test/unit'
require 'pp'

class TestBinary < Test::Unit::TestCase
    def setup
        @data = Array.new(64)
        srand(1)
        @data.each_with_index do |value,index|
            @data[index] = rand(128)
        end

        @bin = Binary.new( @data )
    end

    def test_find_1_returns_index_1
        assert_equal( 1, @bin.find( 1 ))
    end

    def test_find_22_returns_index_18
        assert_equal( 18, @bin.find( 22 ))
    end
end

binary.rb

#!/usr/bin/ruby

class Binary

    def initialize( data )
        self.data( data )
    end

    def data( data )
        @data = data.sort
    end

    def find( value )
        min = 0
        max = @data.count - 1
        while( min <= max )
            mid = ((max + min) / 2).to_i
            if ( value < @data[mid] )
                max = mid-1
            elsif ( value > @data[mid] )
                min = mid+1
            else
                return mid
            end
        end
        return
    end
end

Gotcha: OSX and RVM

Installing RVM created a .bash_local file for its config which prevented .profile from being loaded.

Bash uses the following precedence for profile files, and on finding one will then not look for subsequent profiles:

  • .bash_profile
  • .bash_login
  • .profile

rbenv install

Personal tools