Ideally, you should avoid having getters or setters altogether. The fundamental tenet of OO is behavioral abstraction, your objects should do stuff, not just "store" stuff.
If you absolutely must have getters and setters, the best thing to do would be to actually stick to standard Ruby conventions:
def content_type=(content_type_uid)
@content_type = content_type_uid
# do something with @content_type
end
If that is not possible, you could try to "overload" the method based on arity:
def content_type(content_type_uid = getter = true)
return @content_type if getter
@content_type = content_type_uid
# do something with @content_type
end
If you do this, you should look up how to document this method as two distinct "overloaded" methods in whatever documentation system you are using. E.g. YARD has an @overload
tag:
# @overload content_type
# Gets the content type
# @return [ContentType] The content type
# @overload content_type(content_type_uid)
# Sets the content type to +content_type_uid+
# @param content_type_uid [ContentType::Uid] The UID of the content type to set
def content_type(content_type_uid = getter = true)
return @content_type if getter
@content_type = content_type_uid
# do something with @content_type
end
Or, you could use YARD's support for synthetic attributes/methods:
# Sets the content type to +content_type_uid+
# @param content_type_uid [ContentType::Uid] The UID of the content type to set
def content_type(content_type_uid = getter = true)
return @content_type if getter
@content_type = content_type_uid
# do something with @content_type
end
# !attribute [r] content_type
# Gets the content type
# @return [ContentType] The content type
Note however, that this "overloading" has a significant disadvantage: while you can represent it in documentation, there is no way to represent it in the language. So, when you (as I often do) use reflection to explore some unfamiliar API, you will only see one method with an optional parameter with no indication of the fact that that one method is really two different methods in disguise:
method(:content_type).parameters
#=> [[:opt, :content_type_uid]]
Normally, an optional parameter is used to supply, well, optional arguments, not switch between two completely different behaviors.