Feb15

Sinatra::Base,the modular app, me and this stupid blog post title

sinatra modular | comments

Did you ever dreamed with Modular Apps on Sinatra? Me too!

After all building a ‘bare bones’ Sinatra web app is quit simple, let’s see…

First we need to read about the difference about Sinatra and Sinatra::Base

Some sources of interest are:

config.ru
require 'bundler/setup'
Bundler.require(:default)

require File.dirname(__FILE__) + "/main.rb"


map "/" do
	run BONES::Main
end

map "/dashboard" do
 	run BONES::Dashboard
end

map "/app1" do
 	run BONES::App1
end

map "/app2" do
	run BONES::App2
end

map "/app3" do
	run BONES::App3
end
Gemfile
source "http://rubygems.org"

gem "rack"
gem 'sinatra', :require => 'sinatra/base'
gem "haml"
gem "thin"

Installing this gems

$ sudo gem install bundler
$ sudo gem install sinatra haml thin

and preparing your project

$ bundle install
main.rb
require File.dirname(__FILE__) + "/lib/helpers.rb"


module BONES


  class Main < Sinatra::Base 
    helpers XIXA::Helpers
   
    configure :development do
	    enable  :sessions, :clean_trace, :inline_templates
	    disable :logging, :dump_errors
	    set :static, true
	    set :public, 'public'
    end

    enable :static, :session
    set :root, File.dirname(__FILE__)
    set :custom_option, 'hello'
        
    set :haml, { :format => :html5 }
    
    #set :views, "/path/to/views"
    #set :public, "/path/to/static/files"
   
   get '/' do
    hi("check out")
   end
   
    get '/ip' do
      begin
        @ip = request.env['REMOTE_ADDR'].split(',').first
        haml :index
      rescue
        haml :error
      end
    end
    
    get '/hi' do
      hi("dude")
    end

    get '/sinatra' do
      out = "Powered by Sinatra v#{Sinatra::VERSION} running in '#{Sinatra::Base.environment}' mode.\n"
      erb( out )
    end

  end


  class Dashboard < Main
    helpers XIXA::Helpers
    
    #set :views, "/apps/dashboard/views"
    #set :public, "/path/to/more/static/files"
  
    # using helpers XIXA::Helpers
    get '/' do
      hi('dashboard')
    end
    
    # Sinatra: multiple route patterns / same action
    ['/foo', '/bar'].each do |pattern|
      get pattern do
        strong "Hello World! under Dashboard app"
      end
    end

  end


  class App1 < Main
    helpers XIXA::Auth
  
    # using helpers XIXA::Auth
    get '/' do
      hi("App1")
    end
  
    get '/list' do
      'app1/list'
    end
  
  end

  
  class App2 < Main
  
    get '/hi' do
      'app2/hi'
    end

    get '/hi/dude' do
      'app2/dude'
    end
    
    get '/getappname' do
      haml :index
    end

  end


  class App3 < Main
    helpers XIXA

    # using class Bang on module XIXA
    x = Bang.new
    y = x.lol("OLAAA")

    get '/' do
      "x: #{x.lol("BITCH")} <br /> y: #{y} <br> #{appname}"
    end

  end


end

__END__

@@ layout
%html
  = yield

@@ index
!!!
%html
  %head
    %title
      Your IP is
      = @ip
    
  %body
    %h1
      Your IP is
      %em
        = @ip

      Appname
      %em
        = appname
        
@@ error
not found
lib/helpers.rb
module XIXA


  module Helpers

    def hi(text)
      "Module Helpers: Ola #{text}"
    end

    def em(text)
      "<em>#{text}</em>"
    end
    
    def strong(text)
      "<strong>#{text}</strong>"
    end

    def base_url
      @base_url ||= "#{request.scheme}://#{request.host}#{request.script_name}"      
    end
  
    def appname
      appname = self.class
    end

  
  end


  module Auth

    def hi(text)
      "Module Auth: KAZAM #{text}"
    end

  end


  class Bang

    def lol(text)
      "Module XIXA: Class bang: method Lol: #{text}"
    end

  end


end

finally let’s rock…

$ thin start -R config.ru
>> Thin web server (v1.2.7 codename No Hup)
>> Maximum connections set to 1024
>> Listening on 0.0.0.0:3000, CTRL+C to stop

and point your web browser to that routes :)

have fun

PS: I will update this post later with additional notes; for now it’s working :)

Dec15

Fukkk Offf - Bl00dfuck

music emotions | comments

EMOTION: Need a fucking restart or huge vacations…

Dec14

RadiantCMS on Dreamhost

radiantcms dreamhost | comments

Today tips goes to RadiantCMS, yep that awesome RoR CMS

RadiantCMS wiki
### Installing RadiantCMS on Dreamhost - 14/12/2010
 
$ gem install radiant
$ gem install will_paginate
$ gem install compass
 
$ radiant --mysql /home/USERNAME/YOURAPPIR
 
# ...just follow default install procedure and at the end...
 
$ cd YOURAPPDIR
 
$ rake gems:unpack
 
$ cd vendor/gems
$ gem unpack compass
 
# Edit config/environment.rb and change
# this line:
config.gem 'will_paginate', :version => '~> 2.3.11', :source => 'http://gemcutter.org'
 
 
# by this:
config.gem 'will_paginate', :source => 'http://gemcutter.org'
 
# restart your app
 
$ touch YOUAPPDIR/tmp/restart.txt

http://pastebin.com/CXGnVZKa

have fun

Dec14

Sinatra on Dreamhost

sinatra dreamhost tilt | comments

This is the raw howto install Sinatra 1.0 on Dreamhost.

At this momento, there are some issues with Tilt version used on Sinatra 1.1.0 that Dreamhost Passenger is complaining, so thats why I’m using Sinatra 1.0.

###  Sinatra on Dreamhost - 13/13/2010
 
### Installing Rubygems into another path while using Ruby from Dreamhost (without rvm for now)
 
$ mkdir ~/.gems
$ mkdir ~/bin
$ mkdir ~/lib
 
$ mkdir ~/src
$ cd ~/src
$ wget http://rubyforge.org/frs/download.php/70696/rubygems-1.3.7.tgz
$ tar xzvf rubygems-1.3.7.tgz
$ cd rubygems-1.3.0
$ ruby setup.rb --prefix=$HOME
 
 
### Changing ENV
 
# Add the next 3 lines in to ~/.bash_profile
 
export GEM_HOME="$HOME/.gem"
export GEM_PATH="$GEM_HOME"
export RUBYLIB="$HOME/lib:$RUBYLIB"
 
# also in your ~/.bash_profile change the line bellow
 
export PATH="$HOME/bin:$HOME/.gem/bin:$HOME/.gem/ruby/1.8/bin:$HOME/usr/local/bin:$HOME/usr/bin:$PATH"
 
# load the changed .bash_profile
 
$ source ~/.bash_profile
 
 
### Installing Sinatra and Tilt to ~/.gems
 
$ gem install sinatra -v 1.0
$ gem install tilt -v 1.0
 
$ cd YOURAPP
$ mkdir vendor
 
### unpack gems to your app vendor
 
$ gem unpack sinatra -v 1.0
$ gem unpack tilt -v 1.0
 
 
### config.ru
 
require 'rubygems'
require 'vendor/sinatra-1.0/lib/sinatra.rb'
require 'vendor/tilt-1.0/lib/tilt.rb'
 
set :run, false
set :environment, :production
 
# logging
FileUtils.mkdir_p 'log' unless File.exists?('log')
log = File.new("log/sinatra.log", "a")
$stdout.reopen(log)
$stderr.reopen(log)
 
require 'app'
run Sinatra::Application
 
 
### app.rb
require 'rubygems'
 
get '/' do
  "Hi"
end
 
get '/version' do
  "hello" + Sinatra::VERSION
end

Have fun

Apr27

Getting your hands dirty modeling data with OpenStruct

OpenStruct sinatra | comments

Sometimes building data structures is the way to go when you need to add some configuration structure logic to your application.

There is no need to install any OpenStruct gem. it is built into Ruby Standard Library.

http://www.cs.auckland.ac.nz/references/ruby/stdlib/libdoc/ostruct/rdoc/index.html

Defining the structure

require 'rubygems'
require 'ostruct' #to load osctruct into your app

SiteConfig = OpenStruct.new(
  :name => 'Nagios Event Manager'
)

NagiosLogic = OpenStruct.new(
  :workflow => ['alarm_in', 'rules_proc', 'alarm_transform', 'alarm_out'],
  :alarm_type => [ 'any', 'nagios_service', 'nagios_host', ],
  :alarm_nagios_service => {        # Nagios Service to value relationship
    'any'      => '10',
    'ok'       => '5',
    'warning'  => '3',
    'unknown'  => '4',
    'critical' => '1' },
  :alarm_nagios_host => {           # Nagios Host to value relationship
    'any'         => '10',
    'up'          => '5',
    'unreachable' => '3',
    'down'        => '1' },
  :alarm_rel => {                   # Nagios and HP OpenView relationship
    'any'     => 'any',
    'critial' => 'critial',
    'major'   => '',
    'minor'   => 'unknown',
    'info'    => 'warning',
    'normal'  => 'ok' }		
)

Using the above code

when using erb to build your templates:

<h1><a href="/"><NAGIOS ENVENT MANAGER><%= SiteConfig.name %></a></h1>

or something like:

<select name="at">
  <% NagiosLogic.alarm_type.each do |at|%>
    <option value="<%= at %>"><%= at%></option>
  <% end %>
</select>

when using Sinatra, you can build some validation using your structure and params received in the url.

  NagiosLogic.alarm_nagios_service.each_pair do |key, val|
    params[:ans] = val if key == params[:ans]
  end

pretty easy yhea.

have fun

Apr23

MSTRKRFT - FRSHPRNCFBLR

music | comments

Apr16

Pony, email digest made die simple

pony email | comments

This time it’s about sending emails through your Ruby script.

As usual, let’s install this cool gem:

$ sudo gem install pony

the simple way to use it is:

require 'rubygems'
require 'pony'

Pony.mail(:to      => 'include_yada_gcool.com',
          :from    => 'yourworst@nightmare.com',
          :subject => "Funny thing goes here",
          :body    => "The not so cool spam #{@report.to_yaml} here")

more options are…

require 'rubygems'
require 'pony'

Pony.mail(:to       => 'email@example.com', :via => :smtp, :smtp => {
          :host     => 'smtp.example.com',
          :port     => '25',
          :user     => 'username',
          :password => 'passkey',
          :auth     => :plain,
          :domain   => "example.com"
  },
  :from    => 'me@example.com', 
  :subject => 'hi', 
  :body    => 'Hello there.')

If you are running Ruby 1.9.1 you will get into problems because tmail is (at this time) ‘broken’!

ruby: symbol lookup error: /home/admin/.rvm/gems/ruby-1.9.1-p378/gems/tmail-1.2.7.1/ext/tmailscanner/tmail/tmailscanner.so: undefined symbol: rb_get_kcode

so first uninstall tmail:

$ sudo gem uninstall tmail

and install actionmailler gem:

$ sudo gem install actionmailler

finally add this gem to your greatrubyscriptfile.rb.

require 'rubygems'
require 'action_mailler'
require 'pony'

# your Pony instructions here...

well, you can have this Pony running under simple Ruby scripts or Sinatra/Rails websites. It’s so cool.

blog Post: http://adamblog.heroku.com/past/2008/11/2/pony_the_express_way_to_send_email_from_ruby/

Github: http://github.com/benprew/pony

have fun

Apr15

Rufus Scheduler for my tiny Sinatra Apps

sinatra scheduler | comments

This note is about scheduling tasks deep inside your Ruby script || Sinatra || Rails App.

This gem is so cool because it’s very simple to use and you don’t need to mess up with your system crontab… I’m using this gem to schedule email digests and also something like “service self check” :) … go figure…

To install

$ sudo gem install rufus-scheduler

To get it running

require 'rubygems'
require 'rufus/scheduler'

scheduler = Rufus::Scheduler.start_new

scheduler.cron '00 23 30 * *' do
  # Run every 30 days at 23h00m
  # ...your magic code goes here...
end

quite simple :) . More samples…

scheduler.in '20m' do
  puts "order ristretto"
end

scheduler.at 'Thu Mar 26 07:31:43 +0900 2009' do
  puts 'order pizza'
end

scheduler.cron '0 22 * * 1-5' do
  # every day of the week at 22:00 (10pm)
  puts 'activate security system'
end

scheduler.every '5m' do
  puts 'check blood pressure'
end 

Listing jobs

# returns a map job_id => job of at/in/every jobs
scheduler.jobs

# idem for cron jobs
scheduler.cron_jobs

#idem but for every/at/in/cron jobs (all of them)
scheduler.all_jobs

In this last sample, the script run’s some check at the end of the month and with 5minutes of interval between each one. Pony sends and pretty email with the results:

scheduler = Rufus::Scheduler.start_new

scheduler.cron '00 23 30 * *' do

  @report = Hash.new
  
  # key, value pre-defined hash variable
  puts @total_services_list.to_yaml

  @total_services_list.each do |name,id|
    @report[name.value] = `curl http://resturl/disp/check/#{id}`
    sleep 5 * 60
  end

  Pony.mail(:to => 'include_me_yahda_l.com',
            :from => 'pum@cazam.com',
            :subject => "#{@report}",
            :body => "#{@report.to_yaml}")

end

Advanced topics you can checkout under project website are about: threading, blocks, time strings, :blocking, unschedule, tags, timeouts, exceptions, frequency and even EventMachine.

github: http://github.com/jmettraux/rufus-scheduler/

rdoc: http://rufus.rubyforge.org/rufus-scheduler/

have fun :)

Apr06

nokorigi, libxml2 and Mac OS X

gems osx libxml2 | comments

Let’s avoid the I_KNOW_I_AM_USING_AN_OLD_AND_BUGGY_VERSION_OF_LIBXML2 thing…

First the downloads

$ curl -O ftp://xmlsoft.org/libxml2/libxml2-2.7.7.tar.gz
$ curl -O ftp://xmlsoft.org/libxml2/libxslt-1.1.26.tar.gz

Then the unpack and install

$ tar -xzvf libxml2-2.7.7.tar.gz
$ tar -xzvf libxslt-1.1.26.tar.gz
$ cd libxml2-2.7.7
$ ./configure ; make ; sudo make install
$ cd libxslt-1.1.26
$ ./configure ; make ;  sudo make install

Finally Nokogiri (uninstall your old unlinked and the install the linked one)

$ sudo gem uninstall nokogiri
$ sudo gem install nokogiri -- --with-xml2-include=/usr/local/include/libxml2 --with-xml2-lib=/usr/local/lib

done :)

heve fun

Mar02

STEVE AOKI

MUSIC | comments

Archive