Sha256: 31e01aa3edf1b0f8e0c96580ed0d6bd4e3b4e65b200971f75c9583ec3eadd933

Contents?: true

Size: 1.75 KB

Versions: 8

Compression:

Stored size: 1.75 KB

Contents

# frozen_string_literal: true

module Immoscout
  module Models
    module Concerns
      # Includes functionality to access and modify
      # model attributes transparently.
      module Propertiable
        extend ActiveSupport::Concern

        included do
          cattr_reader :properties, instance_accessor: false do
            {}
          end

          # :reek:ControlParameter - standard stuff, reek!
          # :reek:TooManyStatements
          def method_missing(method_name, *arguments, &block)
            if method_name =~ /build_(\w+)/
              match         = Regexp.last_match(1).intern
              properties    = self.class.properties
              coerce_klass  = properties.fetch(match).fetch(:coerce, nil)
              return super if !properties.key?(match) || !coerce_klass

              send("#{match}=", coerce_klass.new)
            else
              super
            end
          end

          def attributes
            self.class.properties.keys.sort
          end

          # :reek:BooleanParameter - standard stuff, reek!
          def respond_to_missing?(method_name, include_private = false)
            method_name.to_s.start_with?('build_') || super
          end
        end

        class_methods do
          def property(name, **opts)
            attr_accessor(name)

            alias_name = opts.fetch(:alias, false)
            if alias_name
              alias_method alias_name, name
              alias_method "#{opts.fetch(:alias)}=", "#{name}="
            end
            properties[name] = opts
          end

          def find_property(name)
            properties[name] || properties.values.detect do |value|
              value[:alias] == name
            end
          end
        end
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
immoscout-1.6.5 lib/immoscout/models/concerns/propertiable.rb
immoscout-1.6.4 lib/immoscout/models/concerns/propertiable.rb
immoscout-1.6.3 lib/immoscout/models/concerns/propertiable.rb
immoscout-1.6.2 lib/immoscout/models/concerns/propertiable.rb
immoscout-1.6.1 lib/immoscout/models/concerns/propertiable.rb
immoscout-1.6.0 lib/immoscout/models/concerns/propertiable.rb
immoscout-1.5.0 lib/immoscout/models/concerns/propertiable.rb
immoscout-1.4.0 lib/immoscout/models/concerns/propertiable.rb