decorator v1.1.0
Decorator
A simple Crystal shard for decorating objects.
Installation
Add the dependency to your shard.yml
:
dependencies:
decorator:
github: stephendolan/decorator
Run shards install
🎬 Screencast
Watch a LuckyCast on the Decorator shard
Usage
Require the shard:
require "decorator"
Create a decorator Struct
that inherits from Decorator::Base
, and define what it decorates
:
struct TimeDecorator < Decorator::Base
decorates time : Time
# Return a pretty version of a date and weekday in the format:
# `Monday, November 2, 2020`
def date_with_weekday : String
time.to_s("%A, %B %-d, %Y")
end
# Return a pretty version of a date in the format:
# `November 2, 2020`
def date : String
time.to_s("%B %-d, %Y")
end
end
In the above example, Decorator
adds the following to the TimeDecorator
struct for you:
- An
initialize(@time : Time)
method - A
collection(objects : Array(Time))
class method - A
getter
(orgetter?
forBool
types) for@time
Now, you're able to transform Time
objects using the decorator:
decorated_time = TimeDecorator.new(Time.utc)
puts decorated_time.date_with_weekday
# => "Monday, November 2, 2020"
puts decorated_time.date
# => "November 2, 2020"
Or even a collection of time objects with the collection
method:
decorated_times = TimeDecorator.collection([
Time.utc - 1.year,
Time.utc,
Time.utc + 1.year
])
puts decorated_times[0].date_with_weekday
# => "Saturday, November 2, 2019"
puts decorated_times[1].date_with_weekday
# => "Monday, November 2, 2020"
puts decorated_times[2].date_with_weekday
# => "Tuesday, November 2, 2021"
Contributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request
Contributors
- Stephen Dolan - creator and maintainer
Inspiration
- The
decorates
syntax and code mimics the Lucky::Assignable Moduleneeds
implementation created by the Lucky team.
Repository
decorator
Owner
Statistic
- 12
- 1
- 0
- 1
- 1
- about 3 years ago
- December 20, 2020
License
MIT License
Links
Synced at
Sat, 21 Dec 2024 23:23:24 GMT
Languages