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



40
41
42
43
44
45
46
47
48
# File 'lib/permalink_fu.rb', line 40

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


50
51
52
# File 'lib/permalink_fu.rb', line 50

def random_permalink(seed = nil)
  Digest::SHA1.hexdigest("#{seed}#{Time.now.to_s.split(//).sort_by {rand}}")
end


55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/permalink_fu.rb', line 55

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



76
77
78
79
80
81
82
83
84
85
# File 'lib/permalink_fu.rb', line 76

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));
      end
    EOV
  end
  value
end