All posts by adminworks

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.