blog.robotex.de

Expired users in oracle

[ read ]

To view a list of users and their status use following SQL statement:

select username,expiry_date,account_status from dba_users;

To unlock a user:

alter user <USERNAME> identified by <PASSWORD> account unlock;

SQL to see connections in oracle

[ read ]
SELECT username,
       osuser,
       terminal
FROM v$session
WHERE username IS NOT NULL
ORDER BY username ASC;

SQL to check tempspace in oracle

[ read ]
SELECT b.Total_MB,
       b.Total_MB - round(a.used_blocks*8/1024) Current_Free_MB,
       round(used_blocks*8/1024) Current_Used_MB,
       round (max_used_blocks*8/1024) Max_used_MB
FROM v$sort_segment a,
  (SELECT round(sum(bytes)/1024/1024) Total_MB
   FROM dba_temp_files) b;

Ruby on Rails: Get GC info with rack-mini-profiler

[ read ]

Append '?pp=profile-gc' to the url


Access the Active Admin configuration

[ read ]
  > ActiveAdmin.application.default_namespace
  > => :admin

Get the actual encoding of a file on linux

[ read ]

Open a terminal and do:

file -bi [filename]
=> text/plain; charset=utf-8

Rails Admin: Adding models that are defined in an engine

[ read ]

Rails admin is an awesome tool. But when it comes to administer models that are not defined in your application, but in an engine, they simply don't show up.

But....if you manually add them to the model list in an initializer config file, they show up. Assume you have an admin model in your app and a news model inside an engine.

Create Rails.root/config/initializers/rails_admin.rb:

RailsAdmin.config do |config|
  config.included_models = [Admin, News]
end

Now both show up. The only caveat is, that you'll have to manually add all models.


Rails3: Creating engines

[ read ]

There is some documentation about creating rails3 engines here


Rails3: Empty (0 byte) downloads using send_data/send_file

[ read ]

If you get empty downloads served from a rails application on passenger, the culprit might be following line in your Rails.root/environments/production.rb:

config.action_dispatch.x_sendfile_header = "X-Sendfile"

Remove it, and it should work.


Rails: Capybara cheat sheet

[ read ]

There is a capybata cheat sheet here


Devise: disabling sign up

[ read ]

Sometimes you'll need to disable sign up for new users (in this examples "admins") for a site. Here is the recipe.

Disable the sign up routes

In our Rails.root/config/routes.rb:

  devise_for :admins, :skip => :registrations

Remove the sign-up link from the sign-in form

Create Rails.root/app/views/devise/shared/_link.html.erb:

<%- if controller_name != 'sessions' %>
  <%= link_to "Sign in", new_session_path(resource_name) %>
<% end -%> <%- if devise_mapping.recoverable? && controller_name != 'passwords' %> <%= link_to "Forgot your password?", new_password_path(resource_name) %>
<% end -%> <%- if devise_mapping.confirmable? && controller_name != 'confirmations' %> <%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %>
<% end -%> <%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %> <%= link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name) %>
<% end -%> <%- if devise_mapping.omniauthable? %> <%- resource_class.omniauth_providers.each do |provider| %> <%= link_to "Sign in with #{provider.to_s.titleize}", omniauth_authorize_path(resource_name, provider) %>
<% end -%> <% end -%>

In particular, we removed following code from the default template:

<%- if devise_mapping.registerable? && controller_name != 'registrations' %>
  <%= link_to "Sign up", new_registration_path(resource_name) %>
<% end -%>

Rails: display flash messages in your layout

[ read ]

Put following code in your layout (Rails.root/app/views/layout/application.html.erb) to show flash messages:

    <% flash.each do |key, value| %>
      <%= content_tag(:div, value, :class => "flash #{key}") %>
    <% end %> 

Rails3: My conventions

[ read ]

Home site / Root path

  1. The root path routes to the index action of the home controller.

Backend

  1. The default backend is named "admin"
  2. The admin area gets a separte layout in /app/views/layouts/admin.html.erb
  3. Admin controllers extend a controller namend "AdminController"
  4. The admin controller sets the layout

rspec2: generate scaffolds with webrat

[ read ]

When generating a rails scaffold, rspec2 normally does not use webrat. To generate a scaffold with webrat tested views, use the --webrat flag like this:

$> rails g scaffold Event name:string location:string begin_at:timestamp end_at:timestamp link:string description:text --webrat

Ruby: syntactic sugar

[ read ]

This is one of the reasons I love ruby:

Photo.all.map(&:destroy)

Rspec2: date_select vs. i18n

[ read ]

If you get an error like this using i18n on your forms:

  7) Admin::PeopleController as a signed in admin PUT 'update' failure should render the edit template
     Failure/Error: put :update, :locale => @locale, :id => @person, :person => @attrs.merge(:identifier => "")
     ActionView::Template::Error:
       can't convert Symbol into String
     # ./app/views/admin/people/_form.html.erb:44:in `block in _app_views_admin_people__form_html_erb__60110182_108022690__625824326'
     # ./app/views/admin/people/_form.html.erb:1:in `_app_views_admin_people__form_html_erb__60110182_108022690__625824326'
     # ./app/views/admin/people/edit.html.erb:3:in `_app_views_admin_people_edit_html_erb__1032053437_112969930__1009460369'
     # ./app/controllers/admin/people_controller.rb:66:in `block (2 levels) in update'
     # ./app/controllers/admin/people_controller.rb:61:in `update'
     # ./spec/controllers/admin/people_controller_spec.rb:127:in `block (5 levels) in '

You need to add the date format to your Rails.root/config/language.yml:

en:
  date:
    formats:
      default: "%Y-%m-%d"
      short: "%b %d"
      long: "%B %d, %Y"

    order:
      - :year
      - :month
      - :day

Or you get a pre-filled i18n file for your language at [https://github.com/svenfuchs/rails-i18n]


Ruby gems: Installing a specific gem version

[ read ]

Sometime, you'll have to install a specific version of a ruby gem. This is accomplished with th --version parameter.

See following command:

$> gem install rake --version 0.8.7

JForex Strategy Development: Making the currency pair configurable

[ read ]

Adding a property for the currency pair (Instrument) for the user to choose from is really easy:

public class FirstStrategy implements IStrategy {
  @Configurable("Instrument")
  public Instrument selectedInstrument = Instrument.EURUSD;
}

JForex Strategy Development: Simple debug message method

[ read ]
public class FirstStrategy implements IStrategy {
    private void debug(String message) {
        console.getOut().println(message); 
    }
}

Usage:

this.debug("My example debug message!");  // Writes "My example debug message!" to the messages tab

JForex Strategy Development: Basics

[ read ]

As you may have read here before, I've begun to mess around with forex bots.

Currently I have access to live acounts supporting mt4 and jforex.

After having a look at the MetaTrader (version 4) and MQL I decided that I like MQL even less then java. So my next try will be to write a strategy for jforex.

I'll try to collect basic coding tips in this and upcoming posts.

Very basic stuff

  • To compile, the strategy naming must be unique and must match the filename.

Devise: Require customers to be activated before login

[ read ]

Assume you have you have a devise model customer. Customers should be able to sign up, but should be reviewed and activated (i.e. by an admin) before they can login.

First, add a column "active to the customer model:

$> rails g migration AddActiveToCustomers active:boolean

It's a good idea to make the default false:

class AddActiveToCustomers < ActiveRecord::Migration
  def self.up
    add_column :customers, :active, :boolean, :default => false
  end

  def self.down
    remove_column :customers, :active
  end
end

Then you have to customize the inactive message. In your Rails.root/app/modelscustomer.rb:

class Customer < ActiveRecord::Base
  attr_accessible :active # Make the active flag accessible, if you want to set it from anywhere (i.e. in an application backend
  
  def active_for_authentication?
    active
  end 
  
  def inactive_message
    "inactive"
  end 
  .
  .
  .

end

That's it. If a customer signs up, he will not be able to login, before the active flag has been set to true in the database.


x86 PC Emulator written in JavaScript

[ read ]

Some guy (well, he is not really "some guy". See here) has written a PC Emulator in JavaScript that runs in a browser.

Now, this is sick!


Quick chart patterns overview

[ read ]

There is a good cheat-sheet like chart pattern overview at babypips.com here


Ruby: Get filename without extension

[ read ]
file_name = "/foo/bar/baz.txt"
file_name.chomp(File.extname(file_name)) # => "/foo/bar/baz"
File.basename(file_name, '.*') # => "baz"

Cucumber: Integrating rcov

[ read ]

Add the rcov gem to your Rails.root/Gemfile:

group :test do
  gem 'rcov'
end

Then add rcov tasks Rails.root/lib/tasks/rcov.rake:

# Forked to get it working with Rails 3 and RSpec 2
#
# From http://github.com/jaymcgavren
#
# Save this as rcov.rake in lib/tasks and use rcov:all =>
# to get accurate spec/feature coverage data
#
# Use rcov:rspec or rcov:cucumber
# to get non-aggregated coverage reports for rspec or cucumber separately

require 'cucumber/rake/task'
require "rspec/core/rake_task"

namespace :rcov do
  Cucumber::Rake::Task.new(:cucumber_run) do |t|
    t.rcov = true
    t.rcov_opts = %w{--rails --exclude osx\/objc,gems\/,spec\/,features\/ --aggregate coverage.data}
    t.rcov_opts << %[-o "coverage"]
  end
  
  RSpec::Core::RakeTask.new(:rspec_run) do |t|
    t.pattern = 'spec/**/*_spec.rb'
    t.rcov = true
    t.rcov_opts = %w{--rails --exclude osx\/objc,gems\/,spec\/}
  end
  
  desc "Run both specs and features to generate aggregated coverage"
  task :all do |t|
    rm "coverage.data" if File.exist?("coverage.data")
    Rake::Task["rcov:cucumber_run"].invoke
    Rake::Task["rcov:rspec_run"].invoke
  end
  
  desc "Run only rspecs"
  task :rspec do |t|
    rm "coverage.data" if File.exist?("coverage.data")
    Rake::Task["rcov:rspec_run"].invoke
  end
  
  desc "Run only cucumber"
  task :cucumber do |t|
    rm "coverage.data" if File.exist?("coverage.data")
    Rake::Task["rcov:cucumber_run"].invoke
  end
end

Rails3: ActiveRecord-OracleEnhanced-Adapter and jruby

[ read ]

I'm trying to get the oracle enhanced adapter to work on rails3 and jruby. No success till now.

When I try to open a rails console I get following error:

$> rails console
NameError: uninitialized constant ActiveRecord::ConnectionAdapters::AbstractAdapter

Documentation is here

Update: You have to add an oracle initializer (Rails.root/config/initializers/oracle.rb)to get it working:

ActiveSupport.on_load(:active_record) do 
  ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.class_eval do
  .
  .
  .
  end
end

Rails3 on oracle: NoMethodError: undefined method `eq' for nil:NilClass

[ read ]

When try to make simple queries against an oracle database on rails3 and you get following error:

irb(main):017:0> User.find(1)
NoMethodError: undefined method `eq' for nil:NilClass

You may have entered the table name in your model in UPCASE. Change it to downcase, and it should work!


Rails3: Getting it right with jruby and oracle

[ read ]

I finally got rails3 to work with jruby and oracle.

First, you'll need the right gem. Edit your Rails.root/Gemfile like this:

platforms :jruby do
  gem 'activerecord-jdbc-adapter'
end

Then change your Rails.root/config/database.yml to something like this:

development:
  adapter: jdbc
  driver: oracle.jdbc.driver.OracleDriver
  url: jdbc:oracle:thin:@[HOST]:1521:[SID]
  username: foo
  password: bar

Rails3: Getting the base url

[ read ]

I don't know, if there are better ways of getting the base_url in rails, but i've come up with this:

request.url.gsub(request.path, '')

Embedding flash video in html

[ read ]

There is a flash video player for html embedding here.

A embed code generator for the player can be found here.


Installing rails on windows

[ read ]

Prerequisites

You'll need an actual java version.

Install jruby

Download the ruby installer here and install to a directory of your choice (i.e. c:/rubies/jruby_xxx).

Install pik

Go get pik: Download site and run the installer.

Install rails

$> gem install rails

Done!


Rails3 TDD: Capybara != Webrat

[ read ]

Capybara is not a drop-in replacement and does not have the same API. I'll collect differences here:

Webrat Capybara
response.should page.should
contain have_content

Other gotchas: * fill_in does not work with symbols as the fieldname on capybara!


Rails3: form_for and namespaced controllers

[ read ]

Assume you have a Customer model and a namespaced controller for handling customers:

class Platform::Backend::CustomersController < Platform::BackendController
  .
  .
  .
end  

Then, the right form_for tag is the following:

<%= form_for([:platform_backend, @customer]) do |f| %>
  .
  .
  .
<% end %>

Stack level too deep with cucumber and rspec

[ read ]

When you get a "Stack level too deep" error, for all step definitions:

Feature: Create a customer
  
  So that a new customer can access his archive
  As a platform admin
  I want to be able to create a new customer

  Scenario: Create a customer                                   # features/platform_backend/create_a_customer.feature:7
    Given I am logged in                                        # features/platform_backend/step_definitions/create_a_customer_steps.rb:1
    When I create the customer John Doe Company                 # features/platform_backend/step_definitions/create_a_customer_steps.rb:8
      stack level too deep (SystemStackError)
      features/platform_backend/create_a_customer.feature:9:in `When I create the customer John Doe Company'
    Then I should see the John Doe Company in the customer list # features/platform_backend/step_definitions/create_a_customer_steps.rb:15

Failing Scenarios:
cucumber features/platform_backend/create_a_customer.feature:7 # Scenario: Create a customer

1 scenario (1 failed)
3 steps (1 failed, 1 skipped, 1 passed)
0m2.483s

you have been bitten by a bug in rspec v2.5. You can solve this, by specifying a later version in your Rails.root/Gemfile:

group :test, :development do
  gem 'rspec', ">= 2.6.0.rc2"
  gem 'rspec-rails'
end  

Rails: routing root to a placeholder without controller

[ read ]

In your Rails.root/config/routes.rb:

Archive::Application.routes.draw do
  .
  .
  .
  root :to => proc { |env| [200, {}, ["Welcome"]] }
end

Rails3: Applying an application template

[ read ]

Applying a rails application template after having created the applicaton:

rake rails:template LOCATION=/path/to/template

Cucumber: organizing features and steps

[ read ]

I've just written my first feature in cucumber and I'm thinking about the best way to organize features and steps.

I'll give a try at following structure:

Rails.root
|-features
  |-[business_need]
    |-[feature_n].feature
      |- step_definitions
        |- [feature_n]_steps.rb

In reality, it looks like this:

Rails.root
|-features
  |- platform_backend
    |-create_a_customer.feature
      |- step_definitions
        |- create_a_customer_steps.rb

Cucumber and autotest

[ read ]

To have autotest run your cucumber features, you habe to set AUTOFEATURE to true, before running it:

$> AUTOFEATURE=true
$> autotest

Rails3: Installing cucumber

[ read ]

Modify your Rails.root/Gemfile:

group :test do
  gem 'cucumber-rails'
  gem 'capybara'
  gem 'database_cleaner'
end

Install your bundle:

$> bundle install

Install cucumber with rspec and capybara:

$> rails g cucumber:install --capybara --rspec

Japanese candlestick chart cheat sheet

[ read ]

babypips.com has a japanese candlestick chart cheat sheet here


Ruby: Handling zip files

[ read ]

There is a zip gem for Ruby. You can find it here

Creating zip files

First, you have to install the zip gem:

$> gem install zip

or, when using rails, you can add it to your Rails.root/Gemfile:

gem 'zip'

Then you can do something like this:

require 'zip/zip'

Zip::ZipFile.open("output.zip", Zip::ZipFile::CREATE) do |zip_file|
  zip_file.add "filename_in_the_zipfile.txt", "some_source_file.txt"
end

Ruby: Line based file access

[ read ]

Counting lines

I did find some fancy examples, but I wanted to have it look nice, so I came up with this:

File.new('some_file.txt', "r").lines.count

Access a specific line

File.open('some_file.txt', "r") do |file|
  nth_line_content = file.lines.entries[n]
end


Creating a rails3 application with jruby

[ read ]

Create the application:

$> rails new [APP_NAME] -d [DB_ADAPTER] -m http://jruby.org/rails3.rb

Add warbler to your app. Edit Rails.root/Gemfile:

group :development do
  platforms :jruby do
    gem 'warbler'
  end
end

Install your bundle:

$> bundle install

Check the installation:

$> rails server

Open http://localhost:3000.

Deploying to Tomcat

Using sqlite3

If you are using sqlite for production, you may want to include the Rails.root/db to the war file. To do this, you'll have to create a warble config file:

$> warble config

Then, edit Rails.root/config/warble.rb:

Warbler::Config.new do |config|
  config.dirs = %w(app config db lib log vendor tmp)
  .
  .
  .
end

Packiging and move to production

Convert the application to a .war file:

$> warble

Install Tomcat. Copy the .war file to the tomcat/webapps folder. Open a browser at http://localhost:8080/manager (admin:admin) and enable your application.

Open http://localhost:8080/[APP_NAME]

Gotchas

  • The production log is written to [TOMCAT]/log/localhost.YYYY-MM-DD.log

Hausverbot gegen die GEZ rechtens

[ read ]

Wie golem.de berichtet ist ein ausgestelltes Hausverbot gegen die GEZ rechtens und wirksam.

Das ist doch mal eine gute Nachricht. Leider kommt das Urteil (und auch die Klage) etwas spät, da die Zeiten der GEZ-Belästigungen sowieso bald vorbei sein sollten, da bald jeder Haushalt pauschal zahlen "darf".


Blueprint CSS Generator

[ read ]

There is a Blueprint CSS generator at ianli.com


Rails3: nested_scaffold gem

[ read ]

I often use nested resources in rails. And I like to use scaffolds to have a start, when developing. But there is no nested scaffold in rails 3 by default.

Akira Matsuda has written one


FactoryGirl: Defining associations

[ read ]

Assume you have projects that belongs to a customer. You can define a factory like that:

Factory.define(:customer) do |customer|
  customer.email    "customer@example.com"
  customer.password "foobar"
end

Factory.define(:project do |project|
  project.name "Example project"
  project.description "This is an example project"
  project.targeted_at DateTime.now.advance(:days => 7)
  project.association :customer, :factory => :customer
end

Adding pretty URIs to your blog

[ read ]

To add pretty urls to your blogs posts, you can use the friendly_id gem, that can be found here.

The documentation is really good, and installing was straight:

1.Installation

Add the gem to your application. In your Rails.root/Gemfile:

gem "friendly_id", "~> 3.2.1"

Install your bundle:

$> bundle install

Run the friendly id installer:

$> rails g friendly_id

Migrate:

$> rake db:migrate

2.Adding slugs to the post model

Edit Rails.root/app/models/post.rb:

class Post < ActiveRecord::Base
  has_friendly_id :title, :use_slug                    => true, 
                          :approximate_ascii           => true,
                          :ascii_approximation_options => :german # support for german umlauts

Generate the slugs for existing posts:

$> rake friendly_id:make_slugs MODEL=Post

3.Making your posts accessible through nice URIs

There is no step three :)


Rails3: Switch between locales

[ read ]

Assume you have a i18n toolbar on your page. To switch between locales, without switching the current page, you can link to the locale without setting any path:

  <%= link_to image_tag("application/icons/german.jpg"), url_for(:locale => :de) %>
  <%= link_to image_tag("application/icons/english.jpg"), url_for(:locale => :en) %>

Ruby: The set union operator for arrays

[ read ]

I hereby promise, that i'll never forget the "Set Union" operator again.

The Ruby API says: Set Union—Returns a new array by joining this array with other_ary, removing duplicates.

   [ "a", "b", "c" ] | [ "c", "d", "a" ]
          #=> [ "a", "b", "c", "d" ]


Rails3: How to hightlight the current link

[ read ]

Highlighting the current link is a pattern, that you'll need on almost all pages.

I googled the problem and got to this page. Some guy posted a comment with a link to here. I liked the approach from the moment i saw it. Unfortunately it didn't work "out-of-the-clipboard" (seems to be for rails 2.x), so I had tweak it.

Here is what I came up with:

Rails.root/app/helpers/application_helpers.rb:

module ApplicationHelper
  class CurrentPageDecorator
    def initialize(helper,options)
      @helper = helper
      @html_class = options[:class] || 'active'
    end
    
    def link_to(*args,&blk)
      name = args.first
      options = args.second || { }
      html_options = args.third || { }
      if @helper.current_page?(options)
        html_options[:class] = (html_options.has_key?(:class)) ? "#{html_options[:class]} #{@html_class}" : @html_class
      end   
      @helper.link_to(name,options,html_options,blk)
    end
  end

   
  def highlight_current_link(options = { },&blk)
    raise ArgumentError unless block_given?
    yield CurrentPageDecorator.new(self,options)
    nil
  end  
end

In your views:

<ul>
<%= highlight_current_link do |n| %>
  <li class="span-6" id="clinic">
    <%= n.link_to 'Klinik', template_path("praxis/clinic"), :id => 'clinic_link' %>
  </li>

  <li class="span-6" id="office_tour">
    <%= n.link_to 'Office Tour', template_path("praxis/office_tour"), :id => 'office_tour_link' %>
  </li>
<% end %>  
</ul>

To pass a custom html class for the active link you can do:

<%= highlight_current_link(:class => 'on') do |n| %>
.
.
.
<% end %>

Programming language popularity Index

[ read ]

There is a programming language popularity index @ TIOBE Software


The Ruby Toolbox

[ read ]

Sometimes it's difficult to find the best solution or gem for a specific problem in ruby. The Ruby Toolbox has statistics about the popularity of gems orderes in categories:

The Ruby Toolbox


Update: Ostern, *Feier*-Tage und das Frankfurter Ordnungsamt

[ read ]

Die Frankfurter Rundschau hat einen weitern Bericht zum Thema gebracht.

Besonders brisant finde ich die Tatsache, dass diese Aktion mit der christlichen Kirche abgesprochen ist. Zitat aus der FR:

Stein, einstmals Vize des Evangelischen Regionalverbandes, hat sein Eingreifen nach eigenen Worten "mit den beiden großen christlichen Kirchen abgesprochen". Tatsächlich begrüßen die evangelische Pröpstin Gabriele Scherle und der katholische Stadtdekan Stefan Scholz in einer gemeinsamen Erklärung „die entschiedene Haltung“ Steins.

Das muss man sich mal auf der Zunge zergehen lassen! Ich finde das verhalten unseres Ordnungsdezernenten Volker Stein, vor dem Anspruch Frankfurts eine internationale, kultur-offene Großstadt zu sein, völlig inakzeptabel!


Exclude a page from all search robots

[ read ]

To exclude a website from all search robots (google, etc.), you have to create a robots.txt file at its root:

User-agent: *
Disallow: /

Facebook: How to auto-post from your blog

[ read ]

Interesting: ehow.com


Remote Desktop: Using a custom resolution

[ read ]

When connecting to a remote machine via RDP you may specify a resolution on the command line like this:

$> mstsc.exe -v:<remote_host> /w:1280 /h:1024

Ostern, *Feier*-Tage und das Frankfurter Ordnungsamt

[ read ]

Das Frankfurter Orndnungsamt nimmt Ostern dieses Jahr wirklich ernst!

Nach einem Bericht der Frankfurter Rundschau FR Online: "Kein Spaß: Tanzverbot für Osterhasen" wurden einige frankfurter Clubbesitzer (u.a. Mattias Morgenstern, Besitzer des "Tanzhaus West" und Rudi Link, Geschäftsführer vom "Sinkkasten") vom Ordnungsamt angeschrieben und auf ein hessisches Gesetz (von 1952) hingewiesen, dass Tanzveranstaltungen:

  • ab Gründonnerstag um 04:00, bis Samstagnacht um 24:00 Uhr, und
  • ab Ostersonntag um 04:00 Uhr bis Ostermontag um 12:00 Uhr

verbietet. Das Ordnungsamt hätte die Clubs angeschrieben, bei denen es bekannt wäre, dass sie Veranstaltungen Ostern angesagt hätten.

Den Clubbesitzern droht ein Bußgeld in nicht genannter Höhe, sollten sie kontrolliert werden und gegen das Gesetz verstoßen.

In diesen Sinne: Schöne Feier-Tage!


Rails3, Oracle and german umlauts

[ read ]

I'm developing an oracle based rails application with an oracle db using:

  • rails (3.0.3)
  • ruby-oci8 (2.0.4)
  • activerecord-oracle_enhanced-adapter (1.3.2)

German umlauts don't work out-of-the box (for me) and when I start the console, I get following warning:

$> rails c
Warning: NLS_LANG is not set. fallback to US-ASCII.
Loading development environment (Rails 3.0.3)
irb(main):001:0> exit

I suppose that these two things go together.

The official oracle NLS_LANG faq: oracle.com: NLS_LANG FAQ

Solution

Connect to oracle db with sqlplus and issue following command to get the needed NLS_LANG settings:

  SELECT USERENV('LANGUAGE') FROM DUAL; 
    => GERMAN_GERMANY.WE8ISO8859P1

The trick is to set the NLS_LANG environment variable before any gems are loaded. This would be in Rails.root/config/boot.rb:

# Set up oracle parameters
ENV['NLS_LANG'] = 'GERMAN_GERMANY.WE8ISO8859P1'

Voila!


API for Ruby, Ruby on Rails and Rspec

[ read ]

API Dock is a commentable API reference documentation for:

  • Ruby
  • Ruby on Rails
  • Rspec

Learning MQL4

[ read ]

I decided to learn MetaQuotes Language 4 so I can program the MetaTrader.

My understanding is, that you can use all trading operation from inside a script.

What I'm not sure about, is if...

  • you can load orders from a file?
  • you need to write an "Expert Advisor" to do that

First international "Hello World" day

[ read ]

Yesterday, we celebrated the first international "Hello World" day ever!

This day is dedicated to all people, that have ever written or have shown a "Hello World" to others

What is "Hello World"?

Wikipedia says:

A "Hello world" program is a computer program that prints out "Hello world" on a display device. It is typically one of the simplest programs possible in most programming languages. Therefore, by tradition, it is often the first program taught in a beginning class on a particular language. It is also used to illustrate the most basic syntax of a programming language.

Most of these programs are very simple, especially those that rely on a command-line interpreter (shell) to perform the actual output. However, they can be surprisingly complex, especially when writing the program for graphical user interface.

When programming an embedded system, the text may be sent to a liquid crystal display. In a device that does not display text, a simple program to produce a signal, such as turning on an LED, may be substituted for "Hello world" as the introductory program.


My first week as a blogger

[ read ]

I'd never thought it would be that much, but I've written over 20 posts in 7 days!


Git: How to set the commit editor

[ read ]
$> git config --global core.editor "nano"

Using factory girl in your rails projects

[ read ]

Install Factory Girl:

$> gem install factory_girl_rails

Add factory girl to your Rails.root/Gemfile:

group :test do
  gem "factory_girl_rails"
end

Install your bundle:

$> bundle install

If you use rspec2, put your factories in Rails.root/spec/factories.rb:

Factory.define :admin do |admin|
  admin.email    "admin@example.com"
  admin.password "foobar"
end

Rails3: Autoloading /lib with all subdirs

[ read ]

Edit your Rails.root/config/application.rb:

module YourApplication
  class Application < Rails::Application
    .
    .
    .
    config.autoload_paths += %W(#{config.root}/lib)
    config.autoload_paths += Dir["#{config.root}/lib/**/"]
    .
    .
    .
  end
eend


rspec: using rspec in your rails projects

[ read ]

Install the rspec gem:

$> gem install rspec-rails

Add rspec to your Rails.root/Gemfile:

group :test, :development do
  gem "rspec-rails"
end

Install your bundle:

$> bundle install

Generate the basic rspec files:

$> rails g rspec:install

Git: How to start a new rails project and put it on GitHub

[ read ]

Create a new Rails project:

$> rails new <project_name>

Put your rails project under local version control:

$> cd 
$> git init .

Edit the .gitignore file:

.bundle
db/*.sqlite3
log/*.log
tmp/**/*
doc/api
doc/app
*.swp
*~
.project
webrat.log

Commit:

$> git add .
$> git commit -am "Initial commit"

Go to GitHub and create a new project

Add your github master:

$> git remote add origin git@github.com:<your_github_username>/<project_name>.git
$> git push -u origin master

That's it!

After that, a regular commit looks like that:

$> git add .
$> git commit -am "Your commit message"

Pushing to GitHub:

$> git push

Rspec2: Testing the flash in your controller tests

[ read ]
it "should set a flash error message" do
  get :read, :id => @unpublished_post.id
  flash[:notice].should == "This post is not yet published."
end

FactoryGirl: Getting the attributes from a factory

[ read ]

I keep forgetting how to get the attributes of a factory.

From the official documentation:

# Returns a hash of attributes that can be used to build a User instance:
attrs = Factory.attributes_for(:user)

Devise: Testing a custom sessions controller

[ read ]

Assume you have a custom devise sessions controller for your customer login at Rails.root/app/controllers/customers/sessions_controller.rb:

class Customers::SessionsController < Devise::SessionsController
end

To test it with rspec, you'll have to add a before(:each) to the test:

before(:each) do
  setup_controller_for_warden
  request.env["devise.mapping"] = Devise.mappings[:customer]
end

You're test should look like this:

require 'spec_helper'

describe Customers::SessionsController do
  render_views

  before(:each) do
    setup_controller_for_warden
    request.env["devise.mapping"] = Devise.mappings[:customer]
  end

  context "as a visitor" do
    describe "GET 'sign_in'" do
      it "should have an email field" do
        get :new
        response.should have_selector("input[name='customer[email]']")
      end
      
      it "should have a password field" do
        get :new
        response.should have_selector("input[name='customer[password]']")
      end
    end
  end
end

Devise: Customize controller and views

[ read ]

Devise uses built-in controllers and views by default. If you want to customize them, you have to add them to your rails application.

Assume you have a customer login.

Customizing the controller

Create a new controller at Rails.root/app/controllers/customers/sessions_controller.rb:

class Customers::SessionsController < Devise::SessionsController
end

Customize your Rails.root/config.routes.rb to use the controller:

devise_for :customers, :controllers => { :sessions => "customers/sessions" }

Customizing the views

First you'll have to add support for scoped views. Uncomment following lines in your Rails.root/config/initializers/devise.rb:

Devise.setup do |config|
  config.scoped_views = true
end

Then generate the views:

rails generate devise:views customers

Foosball: The snake shot

[ read ]

A very good tutorial about the snake shot can be found at foosmanchu


Using special chars in rails files

[ read ]

Put

# encoding: utf-8

in the first line in files using special chars like german umlauts to avoid errors.


Using the pdf_toolkit gem on Windows

[ read ]

When trying to user the pdf_toolkit gem on windows, I got following error:

     Errno::ENOENT:
       No such file or directory - /dev/null

When you look at the gems source (lib/pdf/toolkit.rb) at line 175, you'll see this:

STDERR.reopen(RUBY_PLATFORM =~ /mswin/ ? 'NUL:' : '/dev/null')

This does not work on my machine. So I created my first monkey patch in new file at Rails.root/lib/pdf_toolkit_patch.rb:

module PDF
  class Toolkit
    class <<self
      private
        def call_program(*args,&block)

          old_stream = nil
          options = args.last.is_a?(Hash) ? args.pop : {}
          options[:mode] ||= 'r' if block_given?
          unless options[:silence_stderr] == false
            old_stream = STDERR.dup
            #STDERR.reopen(RUBY_PLATFORM =~ /mswin/ ? 'NUL:' : '/dev/null')
            STDERR.reopen(RUBY_PLATFORM =~ /i386-mingw32/ ? 'NUL:' : '/dev/null')
            STDERR.sync = true
          end
          if options[:mode]
            command = (args.map {|arg| %{"#{arg.gsub('"','\\"')}"}}).join(" ")
            retval = IO.popen(command,options[:mode],&block)
            retval
            # block_given? ? $?.success? : retval
          else
            system(*args)
          end
        ensure
          STDERR.reopen(old_stream) if old_stream
        end
    end
  end
end

Then I added following line to the file, where I use the pdf-toolkit:

require 'pdf_toolkit_patch'

That's it! My first ruby monkeypatch!


Expect exceptions in rspec2 test

[ read ]

I keep forgetting how to test exceptions with rspec2. This is an example:

  describe "something" do
    describe "exceptions" do
      it "should raise an exception" do
        expect {
          # Code that throws an exception
        }.to raise_error
      end

Capistrano and bundle config

[ read ]

When you use capistrano and you need a custom bundler config in your Rails app, you have the problem, that it gets lost after each update.

The solution to this problem is to move the .bundle folder in your rails app, to the shared folder in your capistrano environment. Then you tell capistrano to link the .bundle to the shared folder after each update.

  • First, move your Rails.root/.bundle to ../../shared/.bundle
  • Add a rake task to Rails.root/config/deploy.rb:
namespace(:bundle) do
  desc "Symlinks your machine specific bundle to your rails app"
  task :symlink, :roles => :app do
    run <<-CMD
      ln -nfs #{shared_path}/.bundle #{release_path}/.bundle
    CMD
  end
end
  • tell capistrano to invoke the bundle:symlink task after symlinking your freshly deployed realase. In your Rails.root/config/deploy.rb:
after "deploy:symlink", "bundle:symlink"


What's next?

[ read ]

After having tried wordpress and some other blog systems, I finally took the time to write my own blogging software. Of course, I used Ruby on Rails to write it.

This Blog runs on DomainFactory (kick-ass RoR Hosting in Germany) and uses:

I'll add support for comments and post categories (tags) asap!


Devise: Testing controllers and requests that need authentication with rspec2

[ read ]

Imagine you have been happily writing your controller test and then, you have to add authentication to your application using devise.

Assume you have a posts controller with following test:

require 'spec_helper'

describe PostsController do
  def mock_post(stubs={})
    @mock_post ||= mock_model(Post, stubs).as_null_object
  end

  describe "GET index" do
    it "assigns all posts as @posts" do
      Post.stub(:all) { [mock_post] }
      get :index
      assigns(:posts).should eq([mock_post])
    end
  end

  describe "GET show" do
    it "assigns the requested post as @post" do
      Post.stub(:find).with("37") { mock_post }
      get :show, :id => "37"
      assigns(:post).should be(mock_post)
    end
  end
end  

First, you'll have to add the Devise TestHelpers. Add a new file spec/support/devise.rb:

RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
end

You'll need a factory for the admin. I use factory girl. Add the admin factory to Rails.root/spec/factories.rb:

Factory.define(:admin) do |admin|
  admin.email    "admin@example.com"
  admin.password "foobar"
end

Then you throw all your controller tests into a new describe block, that signins in your admin before each test:

describe PostsController do
  describe "as a signed in admin" do
    before(:each) do
      admin = Factory(:admin)
      sign_in admin
    end
    
    def mock_post(stubs={})
      @mock_post ||= mock_model(Post, stubs).as_null_object
    end

    describe "GET index" do
      it "assigns all posts as @posts" do
        Post.stub(:all) { [mock_post] }
        get :index
        assigns(:posts).should eq([mock_post])
      end
    end

    describe "GET show" do
      it "assigns the requested post as @post" do
        Post.stub(:find).with("37") { mock_post }
        get :show, :id => "37"
        assigns(:post).should be(mock_post)
      end
    end
  end
end

Customize the request specs. Before:

require 'spec_helper'

describe "NewsItems" do
  describe "GET /news_items" do
    it "works! (now write some real specs)" do
      # Run the generator again with the --webrat flag if you want to use webrat methods/matchers
      get news_items_path
      response.status.should be(200)
    end
  end
end

and with devise integration:

require 'spec_helper'

describe "NewsItems" do
  context "as logged in admin" do
    before(:each) do
      admin = Factory(:admin)
      get new_admin_session_path
      fill_in :email,    :with => admin.email
      fill_in :password, :with => admin.password
      click_button
    end
    
    describe "GET /news_items" do
      it "works! (now write some real specs)" do
        # Run the generator again with the --webrat flag if you want to use webrat methods/matchers
        get news_items_path
        response.status.should be(200)
      end
    end
  end
end

Rake task to create a new devise user

[ read ]
namespace :devise do
  desc "Create admin"
  task :create_admin, :email, :password, :needs => :environment do |t, args|
    if a = Admin.create(:email => args.email, :password => args.password)
      puts "Created admin"
    else 
      puts a.errors
    end    
  end
end  

Usage:

$> rake devise:create_admin["user@example.com","password"]

Markdown online tester and cheat sheet

[ read ]

Add a new role to your site with devise

[ read ]

Adding a new role (i.e. "Admin") is easy:

$> rails generate devise Admin

Don't forget to migrate:

$> rake db:migrate

Then you can check for the admin in your controllers:

class BackendController < ApplicationController
  before_filter :authenticate_admin!
end 

Installing Devise

[ read ]
  • Add the gem to your Gemfile:
gem 'devise'
  • Install your Bundle:
$> bundle install
  • Run the generator:
$> rails generate devise:install

This will generate a initialiter in your config/initializers folder. You should check the options in config/initializers/devise.rb

  • Add default URL options to your mailer configuration in the environments files:

environments/development.rb:

config.action_mailer.default_url_options = { :host => 'localhost:3000' }

environments/production.rb:

config.action_mailer.default_url_options = { :host => 'blog.robotex.de' }

svn:ignore für Rails Projekte

[ read ]

.svnignore Datei im Rails.root erstellen:

.bundle
.project
*.swp
*~
webrat.log
db/*.sqlite3
log/*
tmp/*
doc/api/*
doc/app/*

und danach die Datei "scharf" schalten:

svn -R propset svn:ignore -F .svnignore .