Skip to content

Instantly share code, notes, and snippets.

@avsej
Created September 17, 2010 08:35
Show Gist options
  • Save avsej/583928 to your computer and use it in GitHub Desktop.
Save avsej/583928 to your computer and use it in GitHub Desktop.
dump paperclip attachment urls to json
module PaperclipAttachmentsToJSON
module ClassMethods
def has_attached_file_with_explicit_urls(name, options = {})
has_attached_file_without_explicit_urls(name, options)
# explicit url method definition
url_method = <<-EOM
def %{name}_%{style}_url # def avatar_original_url
%{name}.url(:%{style}) # avatar.url(:original)
end # end
EOM
config = Paperclip::Attachment.default_options.merge(options)
# define url accessor for default style
module_eval(url_method % {:name => name, :style => config[:default_style]})
# define url accessors for each custom styles
config[:styles].each do |style, params|
module_eval(url_method % {:name => name, :style => style})
end
end
end
module InstanceMethods
def to_json_with_attachments(options = {})
options[:methods] ||= []
# enumerate all attachment definitions for the model
self.class.attachment_definitions.each do |key, config|
config = Paperclip::Attachment.default_options.merge(config)
# append default style url accessor
options[:methods] << "#{key}_#{config[:default_style]}_url".to_sym
# append custom sryles url accessors
config[:styles].each do |style, params|
options[:methods] << "#{key}_#{style}_url".to_sym
end
end
to_json_without_attachments(options)
end
alias_method_chain :to_json, :attachments
end
end
ActiveRecord::Base.class_eval do
extend PaperclipAttachmentsToJSON::ClassMethods
include PaperclipAttachmentsToJSON::InstanceMethods
class << self
alias_method_chain :has_attached_file, :explicit_urls
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment