Class: Predicates::HexColor
- Defined in:
- lib/predicates/hex_color.rb
Overview
Defines a field as a hex color. These are hexadecimal strings from 3 to 6 characters long. All hex colors will be saved in the database with a preceding pound sign (e.g. #123456). Also, #123456 is actually a pretty cool color. You should try it.
Instance Attribute Summary
Attributes inherited from Base
#full_message, #or_empty, #validate_if, #validate_on
Instance Method Summary collapse
- #error_message ⇒ Object
-
#like ⇒ Object
a fixed regexp.
- #normalize(value) ⇒ Object
Methods inherited from Pattern
Methods inherited from Base
#allow_empty?, #error, #error_binds, #initialize, #to_human, #validate
Constructor Details
This class inherits a constructor from Predicates::Base
Instance Method Details
#error_message ⇒ Object
8 9 10 |
# File 'lib/predicates/hex_color.rb', line 8 def @error_message ||= :hex end |
#like ⇒ Object
a fixed regexp
4 5 6 |
# File 'lib/predicates/hex_color.rb', line 4 def like @like ||= /\A#[0-9a-fA-F]{6}\Z/ end |
#normalize(value) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/predicates/hex_color.rb', line 12 def normalize(value) return value if value.blank? # ensure leading pound sign value = "##{value}" unless value[0].chr == '#' # expand from three characters to six characters if value =~ /\A#[0-9a-fA-F]{3}\Z/ value = "##{value[1].chr * 2}#{value[2].chr * 2}#{value[3].chr * 2}" end value end |