Sha256: 03332cb01aa9676cb27804e1ae574a2941255e9e617ea7d17400653232369c81

Contents?: true

Size: 1.3 KB

Versions: 4

Compression:

Stored size: 1.3 KB

Contents

# encoding: UTF-8

require "active_model"

# Extension for ActiveModel compatibility
#
# @example
#
#   class Post < Ohm::Model
#     include Ohm::ActiveModelExtension
#   end
module Ohm
  module ActiveModelExtension
    def to_model
      ActiveModelInterface.new(self)
    end
  end

  class ActiveModelInterface
    def initialize(model)
      @model = model
    end

    extend ActiveModel::Naming

    def to_model
      self
    end

    def valid?
      @model.valid?
    end

    def new_record?
      @model.new?
    end

    def destroyed?
      false
    end

    def to_key
      [@model.id] if persisted?
    end

    def persisted?
      ! new_record?
    end

    def to_param
      if persisted?
        @model.respond_to?(:to_param) ?
          @model.to_param :
          @model.id
      end
    end

    def errors
      Errors.new(@model.class.to_reference, @model.errors)
    end

    class Errors
      def initialize(scope, errors)
        @scope  = scope
        @errors = Hash.new { |hash, key| hash[key] = [] }

        errors.each do |key, value|
          @errors[key] << value
        end
      end

      def [](key)
        @errors[key]
      end

      def full_messages
        @errors.map do |key, value|
          I18n::t("ohm.%s.%s.%s" % [@scope, key, value])
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
ohm-contrib-0.1.0 lib/ohm/contrib/active_model_extension.rb
ohm-contrib-0.0.42 lib/ohm/contrib/active_model_extension.rb
ohm-contrib-0.0.41 lib/ohm/contrib/active_model_extension.rb
ohm-contrib-0.0.40 lib/ohm/contrib/active_model_extension.rb