This:
attr_accessor :byte_content
Essentially does:
def byte_content
@byte_content
end
def byte_content=(value)
@byte_content = value
end
Then
alias_method :read, :byte_content
alias_method :write, :byte_content=
will create copies of the byte_content and byte_content= methods with read and write as the new names . If you modify the byte_content or byte_content= methods after the aliasing, the read and write will remain unchanged.
So, the intention of the alias_method in the example appears to be to give the user a more "File-like" interface. Without the method aliases, you would use:
file = MyFile.new
file.byte_content = "abcd"
puts file.byte_content
With the aliases, the user can use:
file = MyFile.new
file.write("abcd")
file.read
Which is quite similar to the methods of the standard library File class,
file = File.open('/tmp/foo.txt', 'w')
file.write('hello')
file.rewind
puts file.read
And this makes it possible to use instances of MyFile in place of real File instances in some very simple use-cases, also known as Duck-typing.
alias vs alias_method
The differences of alias and alias_method are described in the answers to this question, most imporantly:
- you can override
alias_method but not alias
alias_method is used with symbols as the method names, making it useful for dynamically created methods