Sha256: 587cb78429faa36f3650a9eddf4a51f454fd06bbd20455b7f4cb31966ffce03c

Contents?: true

Size: 1.38 KB

Versions: 33

Compression:

Stored size: 1.38 KB

Contents

# -*- encoding : utf-8 -*-
# Helps to define things that will forcibly become floats, integers or strings
module Tracksperanto::Casts
  def self.included(into)
    into.extend(self)
    super
  end
  
  # Same as attr_accessor but will always convert to Float internally
  def cast_to_float(*attributes)
    attributes.each do | an_attr |
      define_method(an_attr) { instance_variable_get("@#{an_attr}").to_f }
      define_method("#{an_attr}=") { |to| instance_variable_set("@#{an_attr}", to.to_f) }
    end
  end
  
  # Same as attr_accessor but will always convert to Integer/Bignum internally
  def cast_to_int(*attributes)
    attributes.each do | an_attr |
      define_method(an_attr) { instance_variable_get("@#{an_attr}").to_i }
      define_method("#{an_attr}=") { |to| instance_variable_set("@#{an_attr}", to.to_i) }
    end
  end
  
  # Same as attr_accessor but will always convert to String internally
  def cast_to_string(*attributes)
    attributes.each do | an_attr |
      define_method(an_attr) { instance_variable_get("@#{an_attr}").to_s }
      define_method("#{an_attr}=") { |to| instance_variable_set("@#{an_attr}", to.to_s) }
    end
  end
  
  def cast_to_bool(*attributes)
    attributes.each do | an_attr |
      define_method(an_attr) { !!instance_variable_get("@#{an_attr}") }
      define_method("#{an_attr}=") { |to| instance_variable_set("@#{an_attr}", !!to) }
    end
  end

end

Version data entries

33 entries across 33 versions & 1 rubygems

Version Path
tracksperanto-3.5.9 lib/tracksperanto/casts.rb
tracksperanto-3.5.8 lib/tracksperanto/casts.rb
tracksperanto-3.5.7 lib/tracksperanto/casts.rb
tracksperanto-3.5.6 lib/tracksperanto/casts.rb
tracksperanto-3.5.5 lib/tracksperanto/casts.rb
tracksperanto-3.5.4 lib/tracksperanto/casts.rb
tracksperanto-3.5.2 lib/tracksperanto/casts.rb
tracksperanto-3.5.1 lib/tracksperanto/casts.rb
tracksperanto-3.5.0 lib/tracksperanto/casts.rb
tracksperanto-3.4.1 lib/tracksperanto/casts.rb
tracksperanto-3.4.0 lib/tracksperanto/casts.rb
tracksperanto-3.3.13 lib/tracksperanto/casts.rb
tracksperanto-3.3.12 lib/tracksperanto/casts.rb
tracksperanto-3.3.11 lib/tracksperanto/casts.rb
tracksperanto-3.3.10 lib/tracksperanto/casts.rb
tracksperanto-3.3.9 lib/tracksperanto/casts.rb
tracksperanto-3.3.8 lib/tracksperanto/casts.rb
tracksperanto-3.3.7 lib/tracksperanto/casts.rb
tracksperanto-3.3.6 lib/tracksperanto/casts.rb
tracksperanto-3.3.0.pre lib/tracksperanto/casts.rb