Skip to content

Change dangerous use of OpenStruct #77

@u0078867

Description

@u0078867

The following:

require 'ostruct'

class Entity < OpenStruct

  def initialize
    super
    @context = "instance var"
  end

end

entity = Entity.new

pp entity.context
pp entity.instance_variable_get("@context")

entity.context = "custom attribute"

pp entity.context
pp entity.instance_variable_get("@context")

will output:

nil
"instance var"
"custom attribute"
"instance var"

However, adding this lines:

require 'ostruct'

class Entity < OpenStruct

  attr_accessor :context   # added

  def initialize
    super
    @context = "instance var"
  end

end

entity = Entity.new

pp entity.context
pp entity.instance_variable_get("@context")

entity.context = "custom attribute"

pp entity.context
pp entity.instance_variable_get("@context")

will output:

"instance var"
"instance var"
"custom attribute"
"custom attribute"

There is a collision between instance variables and OpenStruct custom attributes, of course.

I propose to change to:

class Entity

  attr_accessor :context

  def initialize
    @attributes = OpenStruct.new
    @context = "instance var"
  end

end

@mehmetc do you agree?

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions