A Ruby Struct allows an instance to be generated with a set of accessors:
# Create a structure named by its constant
Customer = Struct.new(:name, :address) #
Personally I use a struct in cases when I want to make a piece of data act like a collection of data instead of loosely coupled under a Hash
.
For instance I've made a script that downloads videos from Youtube and in there I've a struct to represent a Video and to test whether all data is in place:
Video = Struct.new(:title, :video_id, :id) do
def to_s
"http://youtube.com/get_video.php?t=#{id}&video_id=#{video_id}&fmt=18"
end
def empty?
@title.nil? and @video_id.nil? and @id.nil?
end
end
Later on in my code I've a loop that goes through all rows in the videos source HTML-page until empty?
doesn't return true.
Another example I've seen is James Edward Gray IIs configuration class which uses OpenStruct
to easily add configuration variables loaded from an external file:
#!/usr/bin/env ruby -wKU
require "ostruct"
module Config
module_function
def load_config_file(path)
eval <<-END_CONFIG
config = OpenStruct.new
#{File.read(path)}
config
END_CONFIG
end
end
# configuration_file.rb
config.db = File.join(ENV['HOME'], '.cool-program.db')
config.user = ENV['USER']
# Usage:
Config = Config.load_config('configuration_file.rb')
Config.db # => /home/ba/.cool-program.db
Config.user # => ba
Config.non_existant # => Nil
The difference between Struct
and OpenStruct
is that Struct
only responds to the attributes that you've set, OpenStruct
responds to any attribute set - but those with no value set will return Nil