# encoding: utf-8 require_relative "base" module Hexx module Helpers # @api hide # Coerces class attribute getter and setter with given type. # # @example # Coercion.add MyClass, :name, Multibyte::Chars # object = MyClass.new # # object.name = "Ivo" # object.name # # => # class Coercion < Base # @api hide # @!scope class # @!method add(target, name, type) # Reloads the Base class initializer by adding the type of the attribute # to coerce with. # # @example (see Hexx::Helpers::Coercion) # @param (see Hexx::Helpers::Base.add) # @param [Module] type The type of the attribute. # @raise (see Hexx::Helpers::Coercion#validate) # @return [Hexx::Helpers::Coercion] the coercion object. def initialize(target, name, type) super target, name @type = type end # @!attribute type # The type to coerce the attribute with # @return [Class] the type of the attribute attr_accessor :type # @api hide # Validates parameters of the coercion declaration. # # Adds validation of the coercion type to the # {Hexx::Helper::Base#validate}. # # @raise (see Hexx::Helpers::Base.validate) # @raise (see Hexx::Helpers::Coercion#check_type) # @return [Hexx::Helpers::Coercion] +self+ def validate check_type super end private # @api hide # The definition of the coerced attribute getter. # To be reloaded for ActiveRecord models. def getter "def #{ name }=(value); @#{ name } = #{ type.name }.new(value); end" end # @api hide # The definition of the coerced attribute setter. # To be reloaded for ActiveRecord models. def setter "def #{ name }; #{ type.name }.new(@#{ name }); end" end # @api hide # @raise [TypeError] if type is not a class def check_type return if type.is_a? Class fail TypeError.new "#{ type.inspect } is not a class" end end end end