Posts

Access the Active Admin configuration

Dienstag, 29. April 2014, 14:17 Uhr | roberto@vasquez-angel.de |
  > ActiveAdmin.application.default_namespace
  > => :admin

Get the actual encoding of a file on linux

Dienstag, 29. April 2014, 11:32 Uhr | roberto@vasquez-angel.de |

Open a terminal and do:

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

Rails Admin: Adding models that are defined in an engine

Mittwoch, 13. Juli 2011, 23:20 Uhr | roberto@vasquez-angel.de |

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

Mittwoch, 13. Juli 2011, 22:40 Uhr | roberto@vasquez-angel.de |

There is some documentation about creating rails3 engines here

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

Dienstag, 12. Juli 2011, 09:12 Uhr | roberto@vasquez-angel.de |

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

Mittwoch, 06. Juli 2011, 11:27 Uhr | roberto@vasquez-angel.de |

There is a capybata cheat sheet here

Devise: disabling sign up

Samstag, 02. Juli 2011, 12:49 Uhr | roberto@vasquez-angel.de |

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

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

Samstag, 02. Juli 2011, 12:01 Uhr | roberto@vasquez-angel.de |

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

Donnerstag, 30. Juni 2011, 09:02 Uhr | roberto@vasquez-angel.de |

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

Mittwoch, 29. Juni 2011, 13:53 Uhr | roberto@vasquez-angel.de |

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

Donnerstag, 23. Juni 2011, 13:58 Uhr | roberto@vasquez-angel.de |

This is one of the reasons I love ruby:

Photo.all.map(&:destroy)

Rspec2: date_select vs. i18n

Montag, 20. Juni 2011, 21:48 Uhr | roberto@vasquez-angel.de |

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 <top (required)>'

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

Montag, 23. Mai 2011, 14:49 Uhr | roberto@vasquez-angel.de |

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

Freitag, 20. Mai 2011, 12:14 Uhr | roberto@vasquez-angel.de |

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

Freitag, 20. Mai 2011, 12:04 Uhr | roberto@vasquez-angel.de |
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

Freitag, 20. Mai 2011, 11:57 Uhr | roberto@vasquez-angel.de |

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

Mittwoch, 18. Mai 2011, 21:07 Uhr | roberto@vasquez-angel.de |

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

Mittwoch, 18. Mai 2011, 14:45 Uhr | roberto@vasquez-angel.de |

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

Montag, 16. Mai 2011, 01:20 Uhr | roberto@vasquez-angel.de |

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

Ruby: Get filename without extension

Mittwoch, 11. Mai 2011, 13:19 Uhr | roberto@vasquez-angel.de |
file_name = "/foo/bar/baz.txt"
file_name.chomp(File.extname(file_name)) # => "/foo/bar/baz"
File.basename(file_name, '.*') # => "baz"

Cucumber: Integrating rcov

Sonntag, 08. Mai 2011, 18:13 Uhr | roberto@vasquez-angel.de |

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

Donnerstag, 28. April 2011, 13:00 Uhr | roberto@vasquez-angel.de |

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

Donnerstag, 28. April 2011, 12:33 Uhr | roberto@vasquez-angel.de |

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

Donnerstag, 28. April 2011, 10:04 Uhr | roberto@vasquez-angel.de |

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

Mittwoch, 27. April 2011, 21:43 Uhr | roberto@vasquez-angel.de |

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, '')