Sha256: 816861f74007a518df26d2b34798b92d154dbbe61955269d0175c41720cbb850

Contents?: true

Size: 1.23 KB

Versions: 7

Compression:

Stored size: 1.23 KB

Contents

require 'virtus'

class Roqua::CoreApi::Models::ActiveVirtus
  extend  ActiveModel::Naming
  extend  ActiveModel::Translation
  include ActiveModel::Validations
  include ActiveModel::Conversion
  include ActiveModel::Serialization
  include Virtus.model

  def initialize(params = nil)
    super
    dates_from_xi(params)
  end

  def attributes=(params)
    dates_from_xi(params)
    super
  end

  def assign_attributes(params = {})
    self.attributes = params
  end

  private

  # set Date and DateTime attributes by "name(1i)" style params
  def dates_from_xi(params)
    return unless params
    dates_to_change = self.class.attribute_set.select do |a|
      a.type.primitive <= Date && params.key?("#{a.name}(1i)")
    end
    dates_to_change.each do |a|
      date_from_xi(a.name, params)
    end
  end

  def date_from_xi(attribute, params)
    self[attribute] = {
      year:  params.fetch("#{attribute}(1i)"),
      month: params.fetch("#{attribute}(2i)", 1),
      day:   params.fetch("#{attribute}(3i)", 1),
      hour:  params.fetch("#{attribute}(4i)", 0),
      min:   params.fetch("#{attribute}(5i)", 0),
      sec:   params.fetch("#{attribute}(6i)", 0)
    }
  rescue
    errors.add(attribute, I18n.t("errors.messages.invalid_date"))
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
roqua-core-api-0.0.38 lib/roqua/core_api/models/active_virtus.rb
roqua-core-api-0.0.37 lib/roqua/core_api/models/active_virtus.rb
roqua-core-api-0.0.36 lib/roqua/core_api/models/active_virtus.rb
roqua-core-api-0.0.35 lib/roqua/core_api/models/active_virtus.rb
roqua-core-api-0.0.32 lib/roqua/core_api/models/active_virtus.rb
roqua-core-api-0.0.31 lib/roqua/core_api/models/active_virtus.rb
roqua-core-api-0.0.30 lib/roqua/core_api/models/active_virtus.rb