module StringAccessorForArray
Public Class Methods
string_accessor_for_array(attribute, method_name=nil)
click to toggle source
# File lib/buweb/concerns/string_accessor_for_array.rb, line 5 def self.string_accessor_for_array(attribute, method_name=nil) reader_name = method_name || "#{attribute}_string".to_sym writer_name = "#{reader_name}=" # Define a method such as `topics_string` which returns a string # value of the `topics` array. Takes an optional parameter to set separator. # Separator defaults to a comma. # # Example: # topics_string("|") # => "topic1|topic2" define_method(reader_name) do |*args| separator = args.first || "," Array(self.send(attribute)).join(separator) end # Define a method such as `topics_string=` which accepts the string that should # be split into an array, and optionally it accepts the separator to be used. # Separator defaults to a comma. # # Example # topics_string = "hello,world", "," # => ["hello","world"] define_method(writer_name) do |args| string, separator = get_string_and_separator(args) send("#{attribute}=", String(string).split(separator).map(&:strip)) end end
Public Instance Methods
get_string_and_separator(args)
click to toggle source
This adds support for customizing the separator string attribute is either just a string or an array in the format [string, separator]
# File lib/buweb/concerns/string_accessor_for_array.rb, line 36 def get_string_and_separator(args) # defaults if no seperator is given string = args separator = "," # check if seperator is given if args.is_a?(Array) && args.length == 2 separator = args.last string = args.first end [string, separator] end