Sha256: 35fb047171e39d3b2d6126461f299ce9574c71d19a81beaf4a9fc335e9d4105b

Contents?: true

Size: 913 Bytes

Versions: 1

Compression:

Stored size: 913 Bytes

Contents

# frozen_string_literal: true

module Attribeauty
  # base class to inherit from
  # class MyClass < Attribeauty::Base
  class Base
    def self.attribute(name, type)
      @attributes ||= {}
      return if @attributes[name]

      @attributes[name] = type

      class_eval(<<-CODE, __FILE__, __LINE__ + 1)
        def #{name}=(value); @#{name} = Cast.cast(value, #{type.inspect}); end

        def #{name};@#{name};end
      CODE

      return unless type == :boolean

      class_eval(<<-CODE, __FILE__, __LINE__ + 1)
        def #{name}?; !!#{name}; end
      CODE
    end

    def initialize(**attributes)
      attributes.each do |key, value|
        method = "#{key}=".to_sym
        public_send(method, value)
      end
    end

    def assign_attributes(**attributes)
      attributes.each do |key, value|
        method = "#{key}=".to_sym
        public_send(method, value)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
attribeauty-0.1.0 lib/attribeauty/base.rb