Home > Articles > Web Development

The Merb Way: Models

This chapter is from the book

This chapter is from the book

5.7 Plugins

Modularity has been a central objective of DataMapper. Thus, many of the features that you might otherwise expect within a standard ORM are with DataMapper found as plugins. This includes timestamping, aggregation, validations, and various data structures. In this section we’ll go over the most fundamental of these plugins, understanding not only how they’re used but also how they work.

5.7.1 Extra property types

The package dm-types provides numerous additional property types. Here’s a list of those included:

  • BCryptHash—encrypts a string using the bcrypt library
  • Csv—parses strings as CSVs using FasterCSV
  • Enum—stores an enumerated value as an integer
  • EpochTime—converts Time and DateTime to EpochTime, that is, the number of seconds since the beginning of UNIX time
  • FilePath—stores paths as strings using Pathname
  • Flag—binary flags stored as integers
  • IpAddress—IP address stored as a string
  • Json—JSON stored as a string
  • Regexp—regular expressions stored as strings
  • Serial—an auto-incrementing integer type
  • Slug—escapes a stored string, making it suitable to be used as part of a URL
  • URI—stores an Addressable::URI as a string
  • UUID—creates a UUID stored as a string
  • Yaml—stores YAML as a string

Let’s take a look at the source to one of these for a better understanding of how to create our own types:

require 'yaml'

module DataMapper
  module Types
    class Yaml < DataMapper::Type
      primitive String
      size 65535
      lazy true

      def self.load(value, property)
        if value.nil?
        elsif value.is_a?(String)
          raise ArgumentError.new(
            "+value+ must be nil or a String")

      def self.dump(value, property)
        if value.nil?
        elsif value.is_a?(String) && value =~ /^---/

      def self.typecast(value, property)
        # Leave values exactly as they're provided.
    end # class Yaml
  end # module Types
end # module DataMapper

As you can see, new DataMapper types can be created by subclass off of DataMapper::Type. You will then have to set the primitive type, and this can be done using the class method primitive. You may additionally have to set attributes like size and laziness as was done in the case above. Finally, the two methods that do the hard work are the class methods load and dump. These need to be defined only if the custom type needs to override them from simply returning the value. With the Yaml type, strings are converted into YAML when loaded from the database and are converted to strings when they need to be dumped into the database.

5.7.2 Timestamps

The gem dm-timestamps is one of the most commonly used DataMapper plugins. It saves you from having to code timestamping into your models. Note that once the gem is included, it applies to all DataMapper models. Thus we can set the following four properties in any Merb stack model, knowing they will automatically be set when needed:

class User
  property :created_at, DateTime
  property :created_on, Date
  property :updated_at, DateTime
  property :updated_on, Date

Because dm-timestamps is a decently simple plugin but also reveals the foundation of resource extension plugins, let’s take a quick look:

module DataMapper
  module Timestamp
    Resource.append_inclusions self

      :updated_at => [ DateTime,
        lambda { |r, p| DateTime.now } ],

      :updated_on => [ Date,
        lambda { |r, p| Date.today } ],

      :created_at => [ DateTime,
        lambda { |r, p|
          r.created_at ||
            (DateTime.now if r.new_record?) } ],

      :created_on => [ Date,
        lambda { |r, p|
          r.created_on ||
            (Date.today if r.new_record?) } ],

      def self.included(model)
        model.before :create, :set_timestamps
        model.before :update, :set_timestamps
        model.extend ClassMethods


      def set_timestamps
        return unless dirty?
        TIMESTAMP_PROPERTIES.each do |name,(_type,proc)|
          if model.properties.has_property?(name)
            model.properties[name])) unless

    module ClassMethods
      def timestamps(*names)
        raise ArgumentError, '...' if names.empty?

        names.each do |name|
          case name
            when *TIMESTAMP_PROPERTIES.keys
              type, proc = TIMESTAMP_PROPERTIES[name]
              property name, type
            when :at
              timestamps(:created_at, :updated_at)
            when :on
              timestamps(:created_on, :updated_on)
              raise InvalidTimestampName,
              "Invalid timestamp property name '#{name}'"
    end # module ClassMethods

    class InvalidTimestampName < RuntimeError; end
  end # module Timestamp
end # module DataMapper

The first line to notice is the third one. Here the module appends itself to Resource. As we saw earlier in this chapter, this gets the Timestamp module automatically included in all classes that include DataMapper::Resource. Moving on, we see the definition of a number of lambdas to be used in setting the four basic timestamps. This is followed by the class method included, which sets up before hooks to apply the timestamps. It all extends our model classes with a timestamps class method. This is a convenience method for defining the various timestamp properties tersely.

5.7.3 Aggregates

The DataMapper core has been designed to limit its use as a reporting tool and simply act as an ORM. The plugin dm-aggregates consequently adds in some of the most common aggregating methods used by SQL databases:

  • count—finds the number of records in a collection by directly using a count SQL statement and not the Ruby size method
  • min—finds the minimum value of a numerical property using SQL
  • max—finds the maximum value of a numerical property using SQL
  • avg—finds the average value of a numerical property using SQL
  • sum—totals the values of a numerical property using SQL

Chances are you will use dm-aggregates at some point. However, before we look into the source, it’s best to recognize that the plugin essentially extends DataMapper’s capability to what it was not really meant to do.

module DataMapper
  class Collection
    include AggregateFunctions


    def property_by_name(property_name)

  module Model
    include AggregateFunctions


    def property_by_name(property_name)

  module AggregateFunctions
    def count(*args)
      query = args.last.kind_of?(Hash) ? args.pop : {}
      property_name = args.first

      if property_name
        assert_kind_of 'property',
          property_by_name(property_name), Property

      aggregate(query.merge(:fields =>
        [ property_name ?
          property_name.count : :all.count ]))

  module Adapters
    class DataObjectsAdapter
      def aggregate(query)
          query.bind_values) do |reader|

          results = []

          while(reader.next!) do
            row = query.fields.zip(
              reader.values).map do |field,value|

              if field.respond_to?(:operator)
                send(field.operator, field.target, value)

            results << (query.fields.size > 1 ?
              row : row[0])



      def count(property, value)

      module SQL

        alias original_property_to_column_name

        def property_to_column_name(repository,
          property, qualify)
            case property
             when Query::Operator
                 property.operator, property.target, qualify)

             when Property, Query::Path
                 property, qualify)

               raise ArgumentError, "..."

         def aggregate_field_statement(repository,
           aggregate_function, property, qualify)

           column_name = if aggregate_function == :count
             && property == :all
             property_to_column_name(repository, property, qualify)

           function_name = case aggregate_function
             when :count then 'COUNT'
             # ...
             else raise "Invalid ... "

       end # module SQL

       include SQL



Above we have included only the code covering the count method. However, it’s easy to recognize the substantial monkey patching going on, particularly in the case of the SQL methods. Otherwise, though, this is a great example of the trickling down of method calls from collections and models into the adapter where SQL statements are formed.

5.7.4 Validations

The plugin dm-validations validates the property values of model objects before saving them. This means that if a model object returns false upon save, you can most likely interpret it as having been caused by undesirable values on properties. Another way to check if a particular model is valid is to directly use the valid? method that is squeezed in before create or update. Before we go any further, here’s a list of the validation methods available within your models through dm-validations:

  • validates_present—validates the presence of an attribute value.
  • validates_absent—validates the absence of an attribute value.
  • validates_is_accepted—validates that an attribute is true or optionally not false through :allow_nil => true. It can also work with a custom set of acceptance values using :accept => [values].
  • validates_is_confirmed—validates the confirmation of an attribute with another attribute, for instance, matching password and password_confirmation. The default confirmation attribute is the original attribute ending in _confirmation, but :confirm can be used to set it to anything else.
  • validates_format—validates the format of an attribute value against a regular expression or Proc associated by :with. Alternatively, it can be used with predefined formats such as Email and Url through :as. The :allow_nil key is also available.
  • validates_length—validates the value of a numeric against a :min or :max value. Alternatively, a range can be used along with :within.
  • validates_with_method—validates either the model as a whole or a specific property through a method. If only one parameter is given, it is the symbolic form of the method to check the entire model. If two are given, they are the attribute and the method used to check that attribute. Error messages can be passed as true by returning an array where false is the first element and a string for an error message is the second from the validating method.
  • validates_with_block—like validates_with_method but uses blocks. You can validate either against the whole model or a specific attribute as well as pass in error messages.
  • validates_is_number—validates that the value of an attribute is a number, appropriate for use in checking the precision and scale of floats.
  • validates_is_unique—validates that the attribute value is unique, either within the scope of the attribute value of all other model objects or some other scope specified by an array of property symbols through :scope. Also accepts :allow_nil to be set.
  • validates_within—validates that an attribute value is within a set of values specified by :set.

Alternatively, instead of directly using the validations methods, you can include particular hash key-and-values on property definitions. Here’s a list of what keys automatically create appropriate validations:

  • :nullable—when set to false, automatically creates a presence validator
  • :length or :size—automatically creates a length validator
  • :format—creates a format validator
  • :set—creates a within validator

Additionally, numerical properties are automatically validated using validates_is_number. To turn off autovalidation on this or any other property type, use :auto_validation => false. Conditions

Validation methods are also capable of generally accepting conditions as Procs assigned to :if or :unless. The single block parameter for these Procs is the resource itself. Thus we can do the following:

class Experiment
  include DataMapper::Resource

  property :id, Serial
  property :name, String
  property :impetus, Text
  property :question, Text
  property :hypothesis, Text
  property :description, Text
  property :conclusion, Text
  property :completed, TrueClass
  property :result, TrueClass

  validates_present :conclusion, :if => proc { |r|
    r.completed? && r.result?

For terseness, DataMapper validations also allow us to specify a method as a symbol instead of a full Proc. Here we require only that an experiment be complete for it to have a conclusion:

validates_present :conclusion, :if => :completed? Contexts

Contexts allow us to do validations with similar conditions, but specified at the point of validation. For instance, assuming we have the same Experiment model from before, we may set different contexts on particular property validations specifying that they must be validated together:

  validates_present :impetus, :when => [:proposal]
  validates_present :question, :when => [:proposal]
  validates_absent :completed, :when => [:proposal]

The array assigned to when is an array of contexts. The default context is known as :default. We can now use these contexts by including them as a parameter with valid?:

exp = Experiment.new(
  :name => 'Great Subjective Experiment',
  :impetus => 'Thoughts on physicalism and the mind',
  :question => 'Is it possible to subjectively test '+
    'the consciousness of other modes of thought '+
    'through their integration with your own?'
  :completed => true)
exp.valid?(:proposal) # => false Errors

Every time a model object is validated, it populates (or empties) a hash of errors accessible through the resource instance method errors. These errors can be used to indicate to a user that something went wrong or otherwise recognize what particular attributes are invalid:

resource.errors.each do |e|
  puts e # => [[:attr_name, ["Error!"]]]

resource.errors.on(:attr_name) # => ["Error!"]
resource.errors.on(:another_attr) # => nil

Notice how errors.on returns nil when there are no errors. Consequently it can be used to test if an error is present on a property. Also note that error messages are given as arrays. This is because multiple validation errors may have occurred on a single attribute.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020