Skip to content

Instantly share code, notes, and snippets.

@furaji
Last active June 29, 2023 07:50
Show Gist options
  • Save furaji/b92a4a7f47037f06ce25ffa2f0361f1d to your computer and use it in GitHub Desktop.
Save furaji/b92a4a7f47037f06ce25ffa2f0361f1d to your computer and use it in GitHub Desktop.
Rails Base Object
class ApplicationForm
include ActiveModel::Model
include ActiveModel::Attributes
def self.copy_validations_from(model)
attribute_types.keys.each do |key|
model.validators_on(key).each do |validator|
validates(key, validator.kind => validator.options)
end
end
end
end
class ApplicationParameter
class_attribute :_attributes_data, default: {}
class << self
def attribute(attr, options = {})
key = options.fetch(:key, attr)
_attributes_data[key] = attr
end
def inherited(subclass)
subclass._attributes_data = {}
end
end
attr_accessor :values
def initialize(hash_attributes)
attributes = hash_attributes.with_indifferent_access
@values = {}
_attributes_data.each do |key, attr|
@values[key] = attributes[attr]
end
end
def to_hash
_attributes_data.each_with_object({}) do |(key, _attr), hash|
hash[key] = respond_to?(key) ? public_send(key) : values[key]
end
end
end
class ApplicationPresenter
include ActiveModel::Model
include ActiveModel::Attributes
end
class ApplicationQuery
class << self
delegate :call, to: :new
end
end
class ApplicationService
private_class_method :new
def self.call(*args)
instance = new(*args)
yield(instance) if block_given?
instance.send(:call)
end
def to_proc
method(:call).to_proc
end
private
def initialize(*args)
return if args.empty?
raise(NotImplementedError, "You must implement #{self.class}##{__method__}")
end
def call
raise(NotImplementedError, "You must implement #{self.class}##{__method__}")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment