Skip to content

Instantly share code, notes, and snippets.

@jaydorsey
Last active October 30, 2025 16:57
Show Gist options
  • Select an option

  • Save jaydorsey/6d9889a42a01a79959d846810742bf2d to your computer and use it in GitHub Desktop.

Select an option

Save jaydorsey/6d9889a42a01a79959d846810742bf2d to your computer and use it in GitHub Desktop.
Ruby attr_accessor overshadowing
# Illustration of a neat thing that footguns me 1x a year
class Foo
attr_accessor :params
attr_reader :val1, :val2, :val3
def initialize(params: {})
@params = params.with_indifferent_access
# The below should either be:
#
# self.params.fetch(:blah, {})
# @params.fetch(:blah, {})
#
# Or you can use a different attr_accessor/initialize keyword so no name collision
#
# The below does not call the attr_accessor, it use a local variable (from the initializer)
@val1 = params.fetch(:foo, 'oops')
@val2 = @params.fetch(:foo, 'oops')
@val3 = self.params.fetch(:foo, 'oops')
end
def call
puts <<~TXT
params #{params}
params.class #{params.class}
val1 #{val1}
val2 #{val2}
val3 #{val3}
TXT
end
end
x = Foo.new(params: {'foo' => 'bar'})
x.call
__END__
# Output is below
params {"foo"=>"bar"}
params.class ActiveSupport::HashWithIndifferentAccess
val1 oops
val2 bar
val3 bar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment