Les pouvoirs d'une mini-Class embarquée
Une Struct permet de créer des sortes de mini-Class qui rassemble des attributs avec la possibilité d'utiliser des méthodes pour y accéder, sans avoir à écrire une classe explicite.
class User
attr_accessor :first_name, :last_name
def initialize first_name, last_name
@first_name = first_name
@last_name = last_name
end
def hello
"Hello #{first_name} #{last_name}"
end
end
==
User2 = Struct.new(:first_name, :last_name) do
def hello
"Hello #{first_name} #{last_name}"
end
end
Quand on veut donner du sens à de la donnée
places = [[40.748817, -73.985428],
[40.702565, 73.992537]]
Place = Struct.new(:latitude, :longitude)
paris = Place.new(48.866667, 2.333333)
paris.longitude
=> 2.333333
vs
Duration = Struct.new(:from_date, :to_date) do
def number_of_days
((to_date - from_date)/(1000*60*60*24)*1000).to_i
end
end
holiday = Duration.new(Time.now, Time.now+12.days)
holiday.number_of_days
=> 12
class GithubUser
def self.search user:
response = GithubApi.search(query: user, type: 'users')
new users: response['items']
end
USER = Struct.new(:login, :avatar_url, :html_url)
def initialize users
@users = users[:users].map do |user|
USER.new(
user['login'],
user['avatar_url'],
user['html_url']
)
end
end
attr_accessor :users
end
User = Struct.new(:size, :brewing_time, :brewing_temp)
colombian = KCup.new(:small, 60, 85)
brewer = Brewer.new(colombian)
expect(brewer.brew).to eq(true)
Pareil mais sans le nommage d'attribut dans la déclaration
france = OpenStruct.new(
country: 'France',
population: 66_900_000
)
=> <OpenStruct country="France" population=66900000>
france.president = 'Macron'
france
=> <OpenStruct country="France" population=66900000 president='Macron'>
+ flexible
+ dynamique
- contraignant
/!\ Beaucoup moins rapide que les Structs ou des Hash