All posts by adminworks

How to download Betway App for iOS and Android

Betway is one of the major British bookmakers. The house can look back on a success story of more than ten years. The mobile offer has also been significantly expanded. We have taken a look at it for you. If you are interested in the Betway app, you should definitely read on.

Betway App for iOS and Android

Basically, Betway offers both a webapp and downloadable apps for iOS and Android. You can use the webapp or native application with any smartphone or tablet. You don’t have to do anything more than enter the address into the designated field of your mobile browser. Thanks to the Responsive Design, the webpage should always be displayed in the perfect size ratio.

With the iOS Betway app, “only” sports betting is possible. Like the iOS application, the Android app is also limited to sports betting. If you are only interested in sports betting, the downloadable app is fully sufficient.

Download Betway app safely

You can get the iOS app for iPhone and iPad from Apple’s AppStore. The AppStore automatically detects whether you visit it with smartphone or tablet and selects the appropriate app.

For all Android owners, the app is available in the bookmaker’s mobile homepage or here: Furthermore, however, you have to allow downloads from unknown sources in the settings of your device in order to be able to install the app after downloading it.


On the Betway app you can click on the big button “Register Now”. The registration form is only one-sided, but very long. At the very end you have to tick the box that you want to receive the welcome bonus offer, otherwise you will miss out. Filling out the form only takes a few minutes. You will be asked only the information that you probably already know from other bookmakers – so name, address, username, password, etc.

Betway Mobile betting program review

At the time of our test, there were just over 30 categories to be found in Betway’s betting program. Thousands of individual bets are waiting for you here. You will find most of the offers in soccer, which should suit most of you. There are also numerous offers for the competitions. You will get your money’s worth if you are interested in the professional leagues or, for example, the cup.

However, we would like to draw your attention to the Betway Boosts category. In this category, Betway has compiled bets across all sports in which you can earn an attractive sports betting bonus. This category rounds off the very positive overall impression that we have gained from the Betway app.

Advantages / Disadvantages

We have taken a closer look at the advantages and disadvantages of the Betway app for you.

Advantages of the Betway App:

  • Simple menu and imaginative design (just look at the icons for the sports).
  • All desktop functions also mobile.
  • App runs very smoothly
  • You can also get the attractive Betway bonus via mobile.

Disadvantages of the Betway app:

  • Settings need to be changed for Android app


Our conclusion on the Betway app: if you like to play on mobile, want to use a technically mature app that has a large betting program and a good worldwide languages output, as well as attractive bonuses, you should reach for Betway. Only the small hurdle that you first have to change the settings for installing the Android app as a small point of criticism.

What to choose: relocate or work from home?

When considering working from home or relocating for your job, it’s important to weigh the pros and cons of each option.

Working from home is less risky; you can keep your day job while working on other projects in the evening or on weekends. It also provides you with more free time to be spent with family and friends.

On the other hand, working online can be done without moving all your belongings to another city. You can choose a city that offers what you’re looking for in terms of work opportunities and lifestyle, and then commute back and forth as needed.

Relocating can bring a lot of new opportunities – meeting new people, trying new things, exploring different cultures. If you’re willing to take the risk, it’s worth the investment.

Relocating your job most definitely will make you meet new friends and experience new adventures. It also can be a great way to learn more about different cultures and lifestyles – working overseas is one of the most rewarding experiences someone could have in their career path. There are many benefits that come along with working from home as well!

How to earn money working from home?

The internet has made working from home a more viable option than ever before. There are now a number of ways to make an income without having to leave your house. One such way is through financial trading.

With that knowledge in hand, you can then start making informed decisions about your trades and hopefully see some success. Remember, always use caution when trading online; it’s easy to lose money on scams if you’re not careful!

If you’re looking for a career in trading – consider CFDs trading. And if you’re already working from home and are looking for ways to increase your income, be sure to check out our tips on how to make more money from home. Good luck!

  1. Trading can be profitable, but it also requires time and learning to do correctly
  2. Remember, always use caution when trading online; it’s easy to lose money if you’re not careful!
  3. For more information on how to get started with financial trading, check out online tutorial series or use demo versions on online trading platforms.

Why CFD Trading?

CFD trading is becoming more and more popular every day. This is because it offers a lot of advantages over traditional trading methods. Let’s take a look at some of the main benefits of CFD trading:

First, CFDs offer high leverage. This means that you can control a larger position than you would be able to with your own money. This gives you the opportunity to make bigger profits, but it also adds an additional risk. If the trade goes against you, you could lose more money than you have invested.

Second, CFDs are available 24 hours a day, five days a week. You can trade whenever market conditions are right for you.

Third, CFDs allow you to trade on margin. This means that you can use CFDs to take advantage of both rising and falling markets.

Fourth, CFDs are very liquid instruments with low transaction costs. There is no need to worry about finding enough buyers or sellers when trading CFDs as there would be with stocks or futures contracts because CFD prices reflect the underlying market price for these assets directly.

Finally, CFDs allow you to trade a wide range of assets. You can trade CFDs on stocks, indices, commodities, and currencies. This gives you the flexibility to trade the markets that interest you most.

So why should you consider trading CFDs? There are a number of reasons: high leverage, 24-hour availability, margin trading, liquidity, and asset diversity. CFD trading offers many advantages over traditional methods and is becoming more popular every day. Give it a try today!


Job relocation can be a good solution, but it comes with many drawbacks! But working remotely doesn’t have to mean putting up with living abroad on top of working long hours. If you want to start working from home you might look into financial trading.

Trading can be profitable, but it also requires time and learning to do correctly. Before you dive in, it’s important to educate yourself on the basics of trading and the risks involved.

So why should you consider trading CFDs? There are a number of reasons: high leverage, 24-hour availability, margin trading, liquidity, and asset diversity. CFD trading offers many advantages over traditional methods and is becoming more popular every day. Give it a try today!

Some Important Questions About Relocate For Job

Reasonable Time To Relocate For A Job

The time it takes to relocate for a job is also addressed in the law. If an employee has worked over 12 months for their employer, they can’t be fired without reasonable warning or opportunity to correct (except in cases where the employer’s business suddenly shuts down because of the financial crisis). Taking into consideration all relevant circumstances, what is a reasonable time will vary from case to case. However, employers should keep these general factors in mind:

  • The distance and travel time to work for both parties;
  • Expenses involved (e.g., moving truck rental)
  • How much notice is required by either party?
  • What type of jobs are involved? Low-paid jobs typically require less relocation period than higher-paid jobs, which involves more complex relocation arrangements.
  • How many workers (i.e., one or more) will be affected and how critical is the labor shortage?
  • The responsibility of the employer is to find a new position for its employees; while on the other hand, employees bear the responsibility to look for new jobs where they are relocated.

Reasons To Relocate For A Job

There are many reasons to relocate for a job. Here are some of the most common reasons:

  • A new job in another place, which is either highly paid or highly qualified;
  • Better working conditions;
  • The chance of promotion;
  • Taking care of family members (e.g., parents with health problems) or being closer to family members (e.g., children studying at university).

It is important to say that relocation benefits vary from one person to another; thus, the main factors of such benefits are:

  • A new job;
  • The number of years that an employee has worked for the company;
  • The wage difference between the old job and the new job.

“For some companies, it makes sense to have employees relocate for a certain period, but retain them on staff after their term is up.”

It’s not just about economics. If you move away from your home overnight, you will feel surprised by how much things change in so little time. You can imagine what you could feel if it were longer than a year.

Reasons To Relocate For A Job

Should I Relocate For A Job?

One of my best friends moved to Washington after she got married. It’s so expensive but her salary was increased by 30%. She likes it now, though. If you’re considering relocating for a job, think about the following:

  • Do I like the location?
  • How much will I be making? Is the money worth the stress and time it takes to move (and find an apartment)?
  • What do people in my profession make in that area? Are they happy with their careers? Will I be satisfied with the work culture or career path?
  • Have I researched housing prices and school districts in that area?

Relocation benefits are available through many companies today. Usually, relocation benefits include moving expenses, temporary housing for up to three months, reimbursement for travel to the area, and help finding an apartment. However, these benefits are usually given only once every five years.

If you’re not ready to move away from your family or if you’d prefer a job that provides more opportunities for advancement within your company, there are other options available. You can ask for a promotion to keep your current job but have it moved closer to home. Your boss may be willing to relocate you instead of hiring another person who would have conflicting priorities because they must still report back to their current office. Another option is telecommuting through the Internet or through telephone conferencing technology. This allows people to work at home or in satellite offices.


Environment specific files and gitignore

I love my Mac for doing development! Textmate and Passenger make it my all-time favorite environment to develop Ruby / Rails in. It does have some very specific “junk” files I don’t want in my git, though.

In the beginning I would include all those files in every project’s .gitignore file. This worked since all my colleagues also work on a Mac with Passenger & TextMate. Recently I’ve come across people with different setups, which made the project’s .gitignore look like this:


After some searching I found you can easily setup a global .gitignore which ignores your environment specific files. Doing so is easy:

# ~/.gitignore

And added this to my global git config

git config --global core.excludesfile ~/.gitignore 

This all makes your .gitignore file much cleaner and more relevant for the project itself.

Ruby and Rails beginner talk

Last night I gave a talk for Zeus about Ruby and Rails, talking about Ruby fundamentals and a short intro to the Rails philosophy and MVC.

I don’t know if you’ll be much with the slides without hearing the talk, but you can find them on

If you want to see the entire presentation you should come to ArrrrCamp, where I’ll be giving it again.

Autoload JQuery Plugins

Rails has the convenient helper javascript_include_tag where you can give up :default, which automatically loads prototype / effects, or with the jrails plugin adds jquery, jquery-ui and jrails.

But when using jQuery you want to use more than those files, you want to use jQuery plugins, or write your own, all in small .

Loading this can be a pain in the ass. Thats why I wrote this little initializer which adds everything in public/javascripts/jquery/*.js to the defaults.

# config/initializers/add_jquery_to_defaults.rb
Dir[File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR,'jquery','*.js')].each do |js|
  ActionView::Helpers::AssetTagHelper.register_javascript_include_default "jquery/#{File.basename(js)}"

Custom ActiveRecord timestamps

Some legacy databases have already defined their own created_at or updated_at fields. They can be easily filled in with ActiveRecord before_save filters, but after implementing this behaviour a few times the urge arose to write something reusable, so I created the custom_timestamps plugin.

With custom_timestamps you can easily define the columns you want to be updated on creation/change

class LegacyModel < ActiveRecord::Base
  set_create_column :creation_time
  set_update_column :change_time

The plugin can be found on github.

ArrrrCamp Belgium

We have been talking between ourselves about hosting a Belgian Ruby conference since the last Railsconf Europe, and we have finally decided to proceed with the idea. Colleague Joren put things in motion and today we’re proud to announce Arrrrcamp, which stands for “About Ruby, Rails, Radiant and Rum Camp”.

The event will take place on friday, May 8th, in Ghent, Belgium. The idea is to have a barcamp-like organisation of talks, where everybody is encouraged to participate by either doing talks, taking pictures, do some hacking, … You can read all about the event on the website.

Application-wide timeranges

In some applications you need to work with time-ranges a lot. Displaying todays messages, a count of all messages that were posted this month, or last month, … ActiveRecord has pretty good support for times and ranges, so you could do it the default way.

Message.find(:all, :conditions => {:created_at =>})

And although this works perfectly it’s not very easy on the eyes. It’s also not very DRY since I need this on a lot of models. It’d be a lot better if I could have it in a scope, like this

So how do we achieve this?

In our config/initializer folder we have a file called timeranges.rb.

# timeranges.rb
TimeRanges = {
  :today      => lambda { },
  :yesterday  => lambda { },
  :this_week  => lambda { },
  :last_week  => lambda { 1.week.ago.beginning_of_week..1.week.ago.end_of_week},
  :this_month => lambda { },
  :last_month => lambda { 1.month.ago.beginning_of_month..1.month.ago.end_of_month }

Which gives us a constant TimeRanges we can use all over the application. So in our Message we define the named_scope in

class Message < ActiveRecord::Base
  named_scope :in, lambda { |period| 
      :conditions => {:created_at => TimeRanges[period].call}

Now we could even make this more DRY and make a module that defines the named_scope when it’s included, but in my application I had a lot of different use-cases for the TimeRanges, and didn’t really need the scope a lot. Leave me a note if you want it in a module but don’t know how to, else it’s an exercise for the interested and easily challenged reader 😉

Testing Forgery Protection

Try to follow here:

I needed to test 1 controller to see if he was not protected from forgery protection, because requests to that controller come from an external source.

So basically I need to test if my code has

skip_before_filter :verify_authenticity_token

In the test environment, the authenticity_token check is disabled. You can re-enable it in your test like this:

class AccountsControllerTest < ActionController::TestCase
  def setup
    AccountsController.allow_forgery_protection = true # Make sure we have forgery protection before filter turned off

When you do a post and you haven’t skipped the filter, the test will fail.

session_lifetime plugin

One of the things I take for granted on the internet is session expiry. I’m used to the fact that if I’m not active for a certain amount of time, I automatically get logged out. This happens with my Online Banking, with ordering tickets online, …. Most information-critical applications have this.

Because of that, I was surprised that Rails doesn’t have this functionality on board. There is no way to set an expiry date on your session. I googled a bit and stumbled upon the dynamic session exp plugin. This gives you the possibility to expire your session through the cookie’s expires-flag.

An example

# in environment.rb

This plugin worked fine until I wanted to send a message to the webuser, informing him why this happened. Because we’re working with the expire-setting in a cookie, this isn’t possible. Because of that, I wrote my own plugin that gave me that possibility.

With session_lifetime you can set after how much time of inactivity your session should expire, you can execute an action when the session expires, and you can set where to redirect_to after session expiry.

An example

class ApplicationController << ActionController::Base
  expires_session :time => 2.hours, :redirect_to => '/login'

  def on_expiry
    flash[:notice] = "Your session has been expired, and you have been logged out."

More information can be found on github.

Missing something?

I wrote this plugin to solve the problems I had with default Rails session handling. If you have an additional need which you think would be great for this plugin, give me a shout at [email protected], or through GitHub, and I’ll be more then happy to implement your proposal.

RailsXLS Revived

RailsXLS is a plugin to generate Excel files from a .rxls view. It uses a Java Bridge to talk to the Jakarta POI library. I’ve used this plugin in a few projects and it works great for generating .xls files.

On a recent project I once again needed an “Export to Excel” feature. The project is on Rails Edge, and apparently there were some changes to how TemplateHandlers are handled since the plugin was written. I dove into the code and recreated the plugin for Rails Edge / 2.2.

You can find the new plugin on github

It’s usage is quite easy:

# in your environment.rb
Mime::Type.register "application/excel", :xls

# in controller
def index
  @clients = Client.all
  respond_to do |speaks|
    speaks.xls { render :layout => false }

# in index.xls.rxls
sheet = workbook.createSheet("Client List")

@clients.each_with_index do |client, index|
  row = sheet.createRow(index)

As you can see there are still some rough patches in the view. I’m working on a wrapper around this, so all obvious tasks can be easily performed.

Any comments/suggestions for the plugin are very welcome! A big thanks to Venkata Subramaniyan for writing the initial plugin, which can be found here

Do Not Forget: NamedScope and dates

One of the scopes I had in a project was from_this_month

class Transaction
  named_scope :from_this_month, :conditions => {:created_at =>}

Which worked great to know all transactions from a user in a certain month. I could do current_user.transactions.from_this_month. When I tested this in developer mode all went well.. Production, however, didn’t work at all.

As we all know, Developer mode reloads classes every time you make a request. Production mode obviously doesn’t, so in Production, the first time you load the page you get a correct time-scope, if you do it a day later, however, the scope is still the same of yesterday. This can be solved with a proc or a lambda, which will get called on each request!

So, just to make sure I never forget, Use a lambda!

class Transaction
  named_scope :from_this_month, lambda { {:conditions => {:created_at =>}} }

Pros and Cons

A recent commit to the Rails github repository had quite some comments. In one of the tests there was the string:

    topic = => "The pros and cons of programming naked.")

After which Mislav Marohnić asked the obvious question:
Commit 4d9a7ab5f5c28820e0b076f9ca44bdd20e19e6ea to rails's rails — GitHub

After which we now have a pretty nice list of all the pro’s and cons of naked programming!

Refactoring: Implementing filtering

For a project at Openminds we needed an implementation for filtering some data from a list with the aid of checkboxes. Our first solution looked like this:

def index
  session[:order_filter] = params[:filter] if params[:filter] 
  session[:order_filter] ||= { :active => '1', :inactive => '1' } 

  if session[:order_filter][:active] == '0' && session[:order_filter][:inactive] == '0'
    @orders = []
  elsif session[:order_filter][:active] == '0'
    @orders = @user.orders.find(:all, :conditions => {:state => 'active'})
  elsif session[:order_filter][:inactive] == '0'
    @orders = @user.orders.find(:all, :conditions => {:state => 'inactive'})
    @orders = @user.orders.find(:all)

So this code takes the filter-parameters from params, or initializes them from defaults, and then does the correct finds.

In the next iteration, I stumbled onto this code and thought to myself “This can be done better”. After making sure the index action was sufficiently covered with tests, I had a go at it, this is what I came up with:

def list
  if && filter.inactive?
      @orders = @user.orders.all
     @orders =
  elsif filter.inactive?
    @orders = @user.orders.inactive
    @orders = []

def filter
  return @filter if @filter
  session[:order_filter] = params[:filter] if params[:filter]
  session[:order_filter] ||= { :active => '1', :inactive => '1' }

  @filter ="Order", session[:order_filter])
helper_method :filter

# search_filter.rb
class SearchFilter
  attr_reader :name

  def initialize name, hash
    @name = name
    hash.each do |key, value|
      instance_eval <<METHOD
        def #{key}?
          #{value} == 1

This code is more readable in my opinion. I extracted the session-storing and parameter-juggling to the filter-method, which then returns a SearchFilter object. Thanks to SearchFilter I can now query filter for set values in a nice way. I can also call filter in my views, which is nicer then calling session[:order_filter][:active]. I also used named_scope instead of doing the finds manually, which improves readability a lot too!

How would you refactor this?

acts_as_state_machine with auto named_scope powers

Rails 2.1 (Soon to be released?) brings us integrated named_scope‘ing. I’ve already mentioned named_scope here and there, and you can find a complete writeup on Ryan Daigle’s Blog

While working on projects on Rails Edge, we used to have the same pattern over and over.

class Mail < ActiveRecord::Base
  include AASM

  aasm_state :created
  aasm_state :sending
  aasm_state :sent
  aasm_state :failed
  aasm_state :delayed

  named_scope :created, :conditions => {:status => 'created'}
  named_scope :sending, :conditions => {:status => 'sending'}
  named_scope :sent, :conditions => {:status => 'sent'}
  named_scope :failed, :conditions => {:status => 'failed'}
  named_scope :delayed, :conditions => {:status => 'delayed'}

For each state we had, we created a named_scope, because it is so great and easy to be able to say Mail.failed.each .... However, this isn’t really DRY, and we can see a clear pattern here. When you think about it, you really should have a scope for every state you define. So I forked from AASM on github and started hacking away.

The result:

class Mail < ActiveRecord::Base
  include AASM

  aasm_state :created
  aasm_state :sending
  aasm_state :sent
  aasm_state :failed
  aasm_state :delayed

>> Mail.failed
=> []
>> Mail.sent
=> [#<Mail id: 1, email: "[email protected]", content: "hallo", :aasm_state: "sent", created_at: "2008-05-21 15:39:38", updated_at: "2008-05-21 15:39:38">, #<Mail id: 2, email: "[email protected]", status: "sent", created_at: "2008-05-21 15:39:39", updated_at: "2008-05-21 15:39:39">]

You can find my named_scope enabled AASM on github. At the moment only the master branch has been patched with my functionality, I’ll do the no_aasm_prefix branch somewhere this evening / tomorrow. Let me know if you’re using it, and what could be better
This has all been implemented in the AASM Core now.

For those interested in the code, this is the bit that does the magic.

module AASM::NamedScopeMethods
  def self.add_named_scope base
    # Don't add unless it's a class which understands `named_scope`
    return unless base.respond_to? :named_scope

    base.extend AASM::NamedScopeMethods::ClassMethods
    base.class_eval do
      class << self
        alias_method :aasm_state_without_named_scope, :aasm_state
        alias_method :aasm_state, :aasm_state_with_named_scope

  module ClassMethods
    def aasm_state_with_named_scope name, options = {}
      aasm_state_without_named_scope name, options

      self.named_scope name, :conditions => {self.aasm_column => name.to_s} unless self.scopes.include?(name)


While testing the plugin we found out 1 gotcha to this: do not define a aasm_state :new, because this will override the constructor of the class, and you’ll lose all creating-functionality.


This is now default AASM behaviour.


I’ve been struggling for the past few hours trying to get the VIES service of the European Union to work with Savon (Ruby SOAP library) in production. It worked in development but timed out in production, and I soon figured out it was only happening when IPv6 was enabled.

The response I would get when requesting the WDSL on IPv6 was a proxy timeout

* About to connect() to port 80 (#0)
*   Trying 2a01:e0b:1:143:62eb:69ff:fe8f:16e6... * Connected to (2a01:e0b:1:143:62eb:69ff:fe8f:16e6) port 80 (#0)
> GET /taxation_customs/vies/checkVatService.wsdl HTTP/1.1
Accept: */*

* HTTP 1.0, assume close after body
< HTTP/1.0 503 Service Unavailable
< Cache-Control: no-cache
< Connection: close
< Content-Type: text/html
< Content-Length: 310
* Excess found in a non pipelined read: excess = 20, size = 310, maxdownload = 310, bytecount = 0
* Expire cleared
* Closing connection #0
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "">
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<h1>Erreur 503</h1>
<h2>Erreur proxy ipv6</

Yet, when I would do the same request with the curl command-line tool I got the correct WSDL. The only difference was the User-Agent, and apparently that was the issue! When I added something in the User-Agent header, the request fell trough. So I changed my SOAP setup to this: do
  wsdl.document = ''
  wsdl.namespace = ''

  http.headers['User-Agent'] = 'Factr Soap Client'
  http.open_timeout = 2
  http.read_timeout = 2

MySQL password hashing in Ruby

An old database used MySQL’s PASSWORD() hashing functionality for storing user credentials. We’re creating a Ruby app now to interface with that database, and wanted to hash the password in ruby. After looking at the code it looked like they just SHA1 hash the password twice and prepend a *. Implementation in Ruby is easy:

require 'digest/sha1'

def hash_mysql_password pass
  "*" + Digest::SHA1.hexdigest(Digest::SHA1.digest(pass)).upcase

Which gives us in MySQL

mysql> SELECT PASSWORD('foo');
| PASSWORD('foo')                           |
| *F3A2A51A9B0F2BE2468926B4132313728C250DBF | 

And in Ruby

>> hash_mysql_password 'foo'
=> "*F3A2A51A9B0F2BE2468926B4132313728C250DBF"

Inlining CSS in ActionMailer 3 (Rails 3.0)

As most of you already know, a bunch of online mail readers (like Hotmail, Gmail, …) don’t handle stylesheets very well, they prefer inline styling (

TamTam is a gem created by Dave Hoover and Brian Tatnall that does all the dirty work for us. Before Rails 3 there was a plugin called inline_css (by the same authors) that used TamTam to automatically inlined all mails sent by ActionMailer. Since Rails 3, however, the ActionMailer internals have changed, and the plugin stopped working.

For my own use I created a module called InlineCss that I include in the mailers I need inlining for. This is the code:

module InlineCss
  def render(*args)
    if (template = args.first[:template]) && template.mime_type.html?
      # Be warned, this code expects a <style> tag in the head of your layout.
      TamTam.inline(:document => super)

This code sees if I am working with a template and if that template has a HTML MIME-type, it inline’s it with TamTam.

In my mailers I just include it. If you want to have this in all mailers, just add an initializer that includes InlineCss in ActionMailer::Base, and it should work

Radiant 0.7.x and Ruby 1.8.4

A client of ours complained that Radiant 0.7.1 was not working out of the box on one of our shared servers. When running the radiant command he got an error:

/usr/lib/ruby/gems/1.8/gems/radiant-0.7.1/vendor/rails/railties/lib/initializer.rb:199:in `set_load_path': undefined method `load_paths' for nil:NilClass (NoMethodError)
  from /usr/lib/ruby/gems/1.8/gems/radiant-0.7.1/vendor/rails/railties/lib/initializer.rb:97:in `run'
  from /usr/lib/ruby/gems/1.8/gems/radiant-0.7.1/lib/radiant/initializer.rb:101:in `run'
  from /usr/lib/ruby/gems/1.8/gems/radiant-0.7.1/bin/../config/boot.rb:72:in `load_initializer'
  from /usr/lib/ruby/gems/1.8/gems/radiant-0.7.1/bin/../config/boot.rb:90:in `load_initializer'
  from /usr/lib/ruby/gems/1.8/gems/radiant-0.7.1/bin/../config/boot.rb:61:in `run'
  from /usr/lib/ruby/gems/1.8/gems/radiant-0.7.1/bin/../config/boot.rb:19:in `boot!'
  from /usr/lib/ruby/gems/1.8/gems/radiant-0.7.1/bin/../config/boot.rb:161
  from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
  from /usr/lib/ruby/gems/1.8/gems/radiant-0.7.1/bin/radiant:3
  from /usr/bin/radiant:19

It worked fine on our other servers, as well as on our local machines, the only thing that was different was the ruby version, which was 1.8.4 on that specific server. Apparently that version handles super a bit different. The solution was to change 1 line in /usr/lib/ruby/gems/1.8/gems/radiant-0.7.1/lib/radiant/initializer.rb:

# In /usr/lib/ruby/gems/1.8/gems/radiant-0.7.1/lib/radiant/initializer.rb line 101:
-     super
+     super(command, configuration)

Using Datamapper On Legacy Databases

Yesterday I had to map a legacy database schema to some Ruby classes. Just before that I had been looking into the advantages of DataMapper, and it looked like the perfect match for my current “challenge”.

from the DataMapper site:

DataMapper only issues updates or creates for the properties it knows about. So it plays well with others. You can use it in an Integration Database without worrying that your application will be a bad actor causing trouble for all of your other processes.

The system

The system is running with 2 databases. One database holds all the information for the legacy app, the other database holds all information for system management.

mysql app
mysql> desc cpClients;
| Field        | Type         | Null | Key | Default | Extra          |
| clientID     | int(255)     | NO   | PRI | NULL    | auto_increment | 
| login        | varchar(255) | NO   | UNI |         |                | 
| pass         | varchar(255) | NO   |     |         |                | 
| type         | int(2)       | NO   |     | 0       |                | 
| traffic      | bigint(255)  | NO   |     | 0       |                | 
| VAT          | varchar(255) | YES  |     | NULL    |                | 
mysql> desc cpURL;
| Field    | Type         | Null | Key | Default | Extra |
| url      | varchar(255) | NO   | PRI |         |       | 
| clientID | int(255)     | NO   |     | 0       |       | 
> exit
mysql management
mysql> desc ftp_users;
| Field        | Type             | Null | Key | Default           | Extra |
| username     | varchar(60)      | NO   | PRI | NULL              |       | 
| password     | varchar(30)      | YES  |     | NULL              |       | 
| homedir      | text             | YES  |     | NULL              |       | 
| shell        | varchar(15)      | NO   |     | /bin/false        |       | 

One Client has many URL’s, One client also has many ftp_users, but the link in that can’t be captured in a simple has many relationship.

Solving it with DataMapper

Setting up the connections

Setting up 2 connections to the databases was quite easy and well documented. I chose the app database to be the default connection, and management as another.

DataMapper.setup(:default, 'mysql://localhost/app')
DataMapper.setup(:management, 'mysql://localhost/management')
Having different database names

The first problem I had was that I wanted the cpClient table to be mapped to the User class, and cpURL to be mapped to a Domain class. This can be solved with storage_names.

class User
    include DataMapper::Resource
    storage_names[:default] = 'cpClients'

class Domain
    include DataMapper::Resource
    storage_names[:default] = 'cpURL'
Defining primary keys

Defining the primary key of my cpURL table was quite easy since DataMapper does natural keys out of the box.

class Domain
  include DataMapper::Resource
  storage_names[:default] = 'cpURL'

  property :url, String, :key => true

Defining the primary key of the cpClients table was a tad more difficult since it was poorly documented. I wanted the property to be called ID, but it should still use clientID in the database. The magic option to this is :field, which allows you to set a custom field for a propery.

class User
    include DataMapper::Resource
    storage_names[:default] = 'cpClients'

    property :id,                    Serial, :field => 'clientID'
Defining associations

The hardest part was defining associations. When I’d just define them with has n without extra options, DataMapper would look for user_id, so I’d have to tell which key was used. Since it wasn’t very well documented I had some failed attempts

has n, :domains, :child_key => 'clientID'
# => +options[:child_key]+ should be Array, but was String (ArgumentError)

has n, :domains, :child_key => ['clientID']
# => ArgumentError: +name+ should be Symbol, but was String 

has n, :domains, :child_key => [:clientID]
# => MysqlError: Unknown column 'client_i_d' in 'field list' (mysql_error_code=0001)

So I need to use a symbol, but apparently DataMapper does some automatic magic to translate keys. When you have a key like me you can disable this magic by changing field_naming_convention’s proc to your own. In the proc we return the stringified value’s name (to_s is needed because the key is given as a symbol)

repository(:default).adapter.field_naming_convention = lambda { |value| }

And then the association worked. Do note the :child_key option needs to be set at both sides.

class User
  has n, :domains, :child_key => [:clientID]

class Domain
  belongs_to :user, :child_key => [:clientID]
Setting models to automatically connect to another database

The FtpUser model automatically needs to connect to the :management database, and there doesn’t seem to be a function to set this. If you temporarily want to connect to another database you can do it with the repository command.

repository(:management) { FtpUser.first }

However, if you want a model to always connect to a database other then the default, defining self.default_repository_name with the correct repository works very well. (Databases are referred to as repositories)

class FtpUser
  include DataMapper::Resource

  def self.default_repository_name

All of this was needed to get my legacy database mapped, I hope some of you find this information useful. If you see things I can do better / different, do let me know in the comments. I’ve only used DataMapper for about 2 hours so some of my assumptions may be way of.

What Is Self? The Complete Guide To Ruby’s Special Variable

In Ruby, what is self? The special variable self in Ruby points to the object that “has” the code is executed at the moment. Self is used all over Ruby: for example, as a variant of local variables, method names and definitions, and constant lookup. In principle, self appears obvious enough; yet in practice, unexpected circumstances may occur that are difficult to resolve because of this so I wrote this article.

Remember, in Ruby, classes, and modules are interchangeable. This action isn’t any different from the instance method behavior we examined in the previous example.

When writing a class, it’s important for the instance variables to be defined within the body of that same class rather than outside of its definition file. self has no meaning if there are no instance variables attached to it – which means they’re not part of any object at all! This might seem like an unusual thing since one would think self should always refer back to itself regardless of what’s going on around it. However, this isn’t true at all when using classes or modules as objects themselves instead of simply defining them. When you use def, self actually becomes equivalent with Object. But by default, every method will have access to other methods and variables inside their own bodies, self-included. So self will refer to the object that’s executing the code, not necessarily what it’s attached to if you’re using class or module objects directly instead of their files!

self is a special variable in Ruby programming language and has different meanings depending on context. For example, self inside method refers back to an instance where the method.

self is also available in blocks and procs. self inside a block will point to the receiver of that block, self outside any definition means current Object (universal) . self comes into play when you are explicitly defining methods within an iterator or block context. This topic can be confusing for newbies so we decided to write a guide about self in ruby today. As always our goal is to make your learning process easier because knowledge should be clear like water.

When compared to “normal” instance or class methods, self-mixed techniques function similarly. This makes sense. Otherwise, the mixin wouldn’t be able to communicate with the class you blended it into. Let’s say you want define method which modifies a given object but still needs access to self. You would use self-mixed technique.

Mixin methods can be defined either within a class or module definition or outside of one using the extended self syntax. A mixin method is available on every instance that includes it through inheritance. The term “instance” here refers to any object who inherits self from its parent (superclass). Any time you dynamically generate an anonymous subclass with include, including new up an anonymous module that mixes in another module, you are creating multiple instances of your classes and modules. So each added mixin becomes available as self inside their associated instances’ context.

self has some very special applications when used via self-defined techniques like mentioned above but’s more than meets the eye!