Module: PermalinkFu::ClassMethods

Defined in:
lib/permalink_fu.rb

Overview

Contains class methods for ActiveRecord models that have permalinks

Constant Summary collapse

CODEPOINTS =

Contains Unicode codepoints, loading as needed from YAML files

Hash.new { |h, k|
  h[k] = YAML::load_file(File.join(File.dirname(__FILE__), "data", "#{k}.yml"))
}

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.decode(string) ⇒ Object



45
46
47
48
49
50
51
52
53
# File 'lib/permalink_fu.rb', line 45

def decode(string)
  string.gsub(/[^\x00-\x7f]/u) do |codepoint|
    begin
      CODEPOINTS["x%02x" % (codepoint.unpack("U")[0] >> 8)][codepoint.unpack("U")[0] & 255]
    rescue
      "_"
    end
  end
end


55
56
57
# File 'lib/permalink_fu.rb', line 55

def random_permalink
  rand(Time.now.to_i**2).to_s(36)
end


60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/permalink_fu.rb', line 60

def self.setup_permalink_fu_on(base)
  base.extend self
  class << base
    attr_accessor :permalink_options
    attr_accessor :permalink_attributes
    attr_accessor :permalink_field
  end

  yield

  if base.permalink_options[:unique]
    base.before_validation :create_unique_permalink
  else
    base.before_validation :create_common_permalink
  end
  class << base
    alias_method :define_attribute_methods_without_permalinks, :define_attribute_methods
    alias_method :define_attribute_methods, :define_attribute_methods_with_permalinks
  end unless base.respond_to?(:define_attribute_methods_without_permalinks)
end

Instance Method Details



81
82
83
84
85
86
87
88
89
90
# File 'lib/permalink_fu.rb', line 81

def define_attribute_methods_with_permalinks
  if (value = define_attribute_methods_without_permalinks) && self.permalink_field
    class_eval <<-EOV
      def #{self.permalink_field}=(new_value);
        write_attribute(:#{self.permalink_field}, new_value.blank? ? '' : PermalinkFu.escape(new_value.to_s, self.class.to_s));
      end
    EOV
  end
  value
end