Home > Articles > Web Development

  • Print
  • + Share This
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?
          nil
        elsif value.is_a?(String)
          ::YAML.load(value)
        else
          raise ArgumentError.new(
            "+value+ must be nil or a String")
        end
      end

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

      def self.typecast(value, property)
        # Leave values exactly as they're provided.
        value
      end
    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
end

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

    TIMESTAMP_PROPERTIES = {
      :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?) } ],
      }.freeze

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

      private

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

    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)
            else
              raise InvalidTimestampName,
              "Invalid timestamp property name '#{name}'"
          end
        end
      end
    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

    private

    def property_by_name(property_name)
      properties[property_name]
    end
  end

  module Model
    include AggregateFunctions

    private

    def property_by_name(property_name)
      properties(repository.name)[property_name]
    end
  end

  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
      end

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

  module Adapters
    class DataObjectsAdapter
      def aggregate(query)
        with_reader(read_statement(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)
              else
                field.typecast(value)
              end
            end

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

          results
        end
      end

      private

      def count(property, value)
        value.to_i
      end

      module SQL
        private

        alias original_property_to_column_name
          property_to_column_name

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

             when Property, Query::Path
               original_property_to_column_name(repository,
                 property, qualify)

             else
               raise ArgumentError, "..."
           end
         end

         def aggregate_field_statement(repository,
           aggregate_function, property, qualify)

           column_name = if aggregate_function == :count
             && property == :all
             '*'
           else
             property_to_column_name(repository, property, qualify)
           end

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

           "#{function_name}(#{column_name})"
         end
       end # module SQL

       include SQL

     end
   end

end

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.

5.7.4.1 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?
  }
end

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?

5.7.4.2 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

5.7.4.3 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!"]]]
end

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.

  • + Share This
  • 🔖 Save To Your Account