Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby setter idiom

I'm working on a Chart class and it has a margin parameter, that holds :top, :bottom, :right and :left values. My first option was to make margin a setter and set values like this:

# Sets :left and :right margins and doesn't alter :top and :bottom 
chart.margins = {:left => 10, :right => 15}

It's nice, because it is clearly a setter, but, after some thought, I think it could be confusing too: the user might think that margins contains only :left and :right values, what is not right. Another option is eliminate = and make it an ordinary method:

chart.margins(:left => 10, :right => 15)

With this syntax, it's easy to figure out what is happening, but it is not a standard setter and conflicts with margins getter. And there's still another option:

chart.margins(:left, 10)
chart.margins(:right, 15)

I don't know what to think about this. For me, it is obvious the method is a setter, but this time I cannot set multiple values with just one call and there's the problem with getter again. I'm relatively new to Ruby and I haven't got used to all the idioms yet. So, what do you think guys? Which is the best option?

like image 757
Lailson Bandeira Avatar asked Jun 24 '26 23:06

Lailson Bandeira


1 Answers

You could also make a Margin class to enjoy the following clear syntax:

class Margin
    attr_accessor :left, :right, :top, :bottom
    ...
end

class Chart
    attr_accessor :margins
    ...
 end


chart.margins.left = 10
puts chart.margins.right
like image 155
paradigmatic Avatar answered Jun 28 '26 00:06

paradigmatic