Skip to content

Instantly share code, notes, and snippets.

@alpaca-tc
Created September 20, 2020 08:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alpaca-tc/c7faaebc5e1cb0ebdbf3284b27216976 to your computer and use it in GitHub Desktop.
Save alpaca-tc/c7faaebc5e1cb0ebdbf3284b27216976 to your computer and use it in GitHub Desktop.
こういうのが欲しいけれど、どうやったらAM::Modelに入りうるだろうか...
module ActiveModelAttributesInspector
# @return [String]
def inspect
values = attributes.map { |key, value| "#{key}: #{value.inspect}" }.join(', ')
%(<#{self.class.name} #{values}>)
end
# @param pp [PP]
#
# @return [void]
def pretty_print(pp)
pp.object_address_group(self) do
pp.seplist(attributes.keys, proc { pp.text(',') }) do |attr_name|
pp.breakable ' '
pp.group(1) do
pp.text attr_name.to_s
pp.text ':'
pp.breakable
pp.pp public_send(attr_name)
end
end
end
end
end
@alpaca-tc
Copy link
Author

example

class YokuaruForm
  include ActiveModel::Attributes
  attribute :text_field, :string
end

pp YokuaruForm.new

before

=> #<YokuaruForm:0x00007fdc05901ee0
 @attributes=
  #<ActiveModel::AttributeSet:0x00007fdc05901e68
   @attributes=
    {"text_field"=>
      #<ActiveModel::Attribute::WithCastValue:0x00007fdc05901e18
       @name="text_field",
       @original_attribute=nil,
       @type=#<ActiveModel::Type::String:0x00007fdbe3bb3bd8 @limit=nil, @precision=nil, @scale=nil>,
       @value_before_type_cast=nil>}>>

after

=> #<YokuaruForm:0x00007fdbe58e5490 text_field: nil>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment