Sha256: 3a94dd38ccd9c8ae0c0860746cc9c14ebf13fff4bc561e5f6450f544b1337178

Contents?: true

Size: 932 Bytes

Versions: 10

Compression:

Stored size: 932 Bytes

Contents

module Hexx
  module Models

    # @api hide
    # Coerces class attribute getter and setter with given type.
    class BaseCoercer < Struct.new(:klass, :name, :type)

      # Coerces class attribute's getter and setter.
      #
      # @example
      #   BaseCoercer.new SomeModel, :name, StrippedString
      #   BaseCoercer.coerce
      #
      #   model = SomeModel.new name: "string"
      #   model.name.class # => StrippedString
      def coerce
        coerce_setter
        coerce_getter
      end

      private

      def coerce_setter
        klass.class_eval(
          "def #{ name };
            #{ type_name }.new(@#{ name });
          end"
        )
      end

      def coerce_getter
        klass.class_eval(
          "def #{ name }=(value);
            @#{ name } = #{ type_name }.new(value);
          end"
        )
      end

      def type_name
        @type_name ||= type.name
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
hexx-5.4.0 lib/hexx/models/base_coercer.rb
hexx-5.3.0 lib/hexx/models/base_coercer.rb
hexx-5.2.0 lib/hexx/models/base_coercer.rb
hexx-5.1.0 lib/hexx/models/base_coercer.rb
hexx-5.0.0 lib/hexx/models/base_coercer.rb
hexx-4.0.0 lib/hexx/models/base_coercer.rb
hexx-3.2.1 lib/hexx/models/base_coercer.rb
hexx-3.2.0 lib/hexx/models/base_coercer.rb
hexx-3.1.0 lib/hexx/models/base_coercer.rb
hexx-3.0.0 lib/hexx/models/base_coercer.rb