3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Elasticsearch::Persistence::Model で Dynamic Attribute

Posted at
class User
  include Elasticsearch::Persistence::Model

  def initialize(attrs = {})
    set_attributes(attrs)
    super attrs
  end

  def set_attributes(attrs = {})
    attrs.each do |attr, value|
      set_attribute(attr, value)
    end
  end

  def set_attribute(attribute, value)
    attribute = attribute.to_sym
    unless self.class.attribute_set.map { |attr| attr.name }.include? attribute
      self.class.attribute attribute, value.class
    end
    send "#{attribute.to_s}=", value
  end

  def []=(attribute, value)
    set_attribute(attribute, value)
  end

  def method_missing(meth, *args, &block)
    if meth.to_s =~ /(.+)=$/
      set_attribute($1, args.first)
    else
      super
    end
  end
end

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?