Method: DataMapper::Is::Published#is_published
- Defined in:
- lib/is/published.rb
#is_published(*args) ⇒ Object
method that adds a basic published status attribute to your model
params
-
states- an array of ‘states’ as symbols or strings. ie: :live, :draft, :hidden
Examples
is :published :on, :off
is :published %w(a b c d)
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 |
# File 'lib/is/published.rb', line 133 def is_published(*args) # set default args if none passed in args = [:live, :draft, :hidden] if args.blank? args = args.first if args.first.is_a?(Array) # the various publish states accepted. @publish_states = args.collect{ |state| state.to_s.downcase.to_sym } @publish_states_for_validation = args.collect{ |state| state.to_s.downcase } extend DataMapper::Is::Published::ClassMethods include DataMapper::Is::Published::InstanceMethods # do we have a :publish_status declared if properties.any?{ |p| p.name == :publish_status } # set default value to first value in declaration or the given value d = properties[:publish_status].default.blank? ? @publish_states.first.to_s : properties[:publish_status].default # set the length to 10 if missing or if shorter than 5, otherwise use the given value l = 5 if properties[:publish_status].length.blank? l = (properties[:publish_status].length <= 10 ? 10 : properties[:publish_status].length) property :publish_status, String, :length => l, :default => d.to_s else # no such property, so adding it with default values property :publish_status, String, :length => 10, :default => @publish_states.first.to_s end # create the state specific instance methods self.publish_states.each do |state| define_method("is_#{state}?") do self.publish_status == state.to_s end define_method("save_as_#{state}") do self.publish_status = state.to_s save end end # ensure we are always saving publish_status values as strings before :valid? do self.publish_status = self.publish_status.to_s if self.respond_to?(:publish_status) end validates_within :publish_status, :set => @publish_states_for_validation, :message => "The publish_status value can only be one of these values: [ #{@publish_states_for_validation.join(', ')} ]" end |