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.

Ruby

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:

.DS_Store
Thumbs.db
tmp/restart.txt
.idea
.todo
.bundle
.rake_tasks~

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

# ~/.gitignore
.DS_Store
tmp/restart.txt
.rake_tasks~
.idea

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 http://defv.be/ruby.and.rails.pdf.

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)}"
end

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
end

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 => Time.now.beginning_of_month..Time.end_of_month})

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

Message.in(:this_month)

So how do we achieve this?

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

# timeranges.rb
TimeRanges = {
  :today      => lambda { Time.now.beginning_of_day..Time.now.end_of_day },
  :yesterday  => lambda { 1.day.ago.beginning_of_day..1.day.ago.end_of_day },
  :this_week  => lambda { Time.now.beginning_of_week..Time.now.end_of_week },
  :last_week  => lambda { 1.week.ago.beginning_of_week..1.week.ago.end_of_week},
  :this_month => lambda { Time.now.beginning_of_month..Time.now.end_of_month },
  :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}
  }
end

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
    super
    AccountsController.allow_forgery_protection = true # Make sure we have forgery protection before filter turned off
  end
end

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
CGI::Session.expire_after 1.day

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'

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

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.html
    speaks.xls { render :layout => false }
  end
end

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

@clients.each_with_index do |client, index|
  row = sheet.createRow(index)
  row.createCell(0).setCellValue(client.id)
  row.createCell(1).setCellValue(client.name)
end

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 => Time.now.beginning_of_month..Time.now}
  ...
end

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 => Time.now.beginning_of_month..Time.now}} }
  ...
end

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 = @target.new(:title => "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'})
  else
    @orders = @user.orders.find(:all)
  end
end

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.active? && filter.inactive?
      @orders = @user.orders.all
  elsif filter.active?
     @orders = @user.orders.active
  elsif filter.inactive?
    @orders = @user.orders.inactive
  else
    @orders = []
  end
end

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

  @filter = SearchFilter.new("Order", session[:order_filter])
end
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
        end
METHOD
    end
  end
end

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'}
end

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
end

...
>> 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
      end
    end
  end

  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)
    end
  end
end

Gotcha

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.

Update

This is now default AASM behaviour.

Savon

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 ec.europa.eu port 80 (#0)
*   Trying 2a01:e0b:1:143:62eb:69ff:fe8f:16e6... * Connected to ec.europa.eu (2a01:e0b:1:143:62eb:69ff:fe8f:16e6) port 80 (#0)
> GET /taxation_customs/vies/checkVatService.wsdl HTTP/1.1
Host: ec.europa.eu
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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Error</title>
</head>
<body>
<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:

Savon::Client.new do
  wsdl.document = 'http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl'
  wsdl.namespace = 'urn:ec.europa.eu:taxud:vies:services:checkVat:types'

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

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
end

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)
    else
      super
    end
  end
end

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       |                | 
<snip>
| 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              |       | 
<snip>
| 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'
end

class Domain
    include DataMapper::Resource
    storage_names[:default] = 'cpURL'
end
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
end

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'
end
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| value.name.to_s }

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]
end

class Domain
  belongs_to :user, :child_key => [:clientID]
end
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
      :services
  end
end

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!

 

The Universal Verification Methodology (UVM): Eliminating Expensive Interfacing and Reuse

The universal verification method (UVM) is a standard that aims to promote IP interoperability among companies that have used the verified virtual mint (VIP). By removing time-consuming interface costs, the UVM will boost production. This article explains how to use UVM techniques to enhance your company’s profitability.

Comprehensive And Flexible Framework

The UVM has been designed to provide a wide and adaptable framework for developing verification models, which in turn can be used by the industry as well.

The Verification Methodology 2.1 (VMM) provides developers access to both high-level conceptual building blocks such as process flows or mathematical representation schemes where low-level complexities would only bog them down – even if they knew how those things worked under their own steam! The Open Source methodology integrated into this release will allow more rapid timetable advances than ever before when dealing primarily with aerospace applications.

The UVM is a powerful verification method that can be really productive in the right hands. Its contribution to UVM World was an open-source design for an SoC, which includes some useful tools and resources including RISC-based components as well as videos about how you use the best.

Advantages

  • Easy to use, for both verification engineers and customers.
  • Supports embedded software development processes
  • An open standard with support from industry leaders.
  • The universal design methodology is a great way to avoid the need for costly interoperability between verification libraries when you are verifying complex SoCs or designs that have multiple clock domains. The UVM provides users with an easy-to-use, base class library which can be extended in unique ways based on project requirements. This article explains why this proven method should be considered during your next IC design process!
  • Best Practices/Ideas To Include: – provide a universal solution avoiding expensive interfaces – eliminate reuse of IP blocks by using the universal methodology – which is easy to use and provides a base class library.

Usage Of UVM

In object-oriented programming, a factory is the most common notion. It’s an object that lets you instantiate other objects and register your item with UVM factories by using one of these registration macros identified above (`uvm_object_utils(A), uvm component utils) or another macro called “u vm wooden”. Alternatively, there are also more creative ways for creating instances such as via `ufactory which offers many creative methods allowing users to customize what instance name their new instance has; this can be useful when registering components because not all types have been registered yet. As mentioned above, it is also possible to create instances by using components. This can be helpful when you need a user object’s instance and the only way for getting one is via its factory (i.e., universal verification methodology).

A scoreboard is used to measure the quality of a design. First, it takes inputs from an electronic device and outputs them as desired by its designers; then there’s determining what those input-output relationships should be like in order for both sides (the DUT) can adhere well enough without any errors happening on either end–judged upon judging whether or not this particular system satisfies its specification through using metrics such as error rate calculations. This process often uses high-level programming languages that SystemC falls under when implementing models onto lower-layer protocols.

self. works_with_ruby?