Last active
October 30, 2025 16:57
-
-
Save jaydorsey/6d9889a42a01a79959d846810742bf2d to your computer and use it in GitHub Desktop.
Ruby attr_accessor overshadowing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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