By default Attachment Fu stores uploaded files in "public/#{table_name}". I want to modify this to be something like "public/#{table_name}/#{site_id}", where site_id is a property of the model. Note that I've tried using self.site_id and both fail.
has_attachment :storage => :file_system,
:max_size => 25.megabytes,
:path_prefix => "public/#{table_name}/#{site_id}",
:thumbnails => {
:large => '256x256>',
:medium => '128x128>',
:small => '64x64>'
}
I receive "undefined local variable or method site_id" error messages. Removing the #{site_id} component from the :path_prefix works fine and the initialize method is run. I can access the site_id as expected.
I have an initialize method which looks like this:
def initialize(site_id = nil)
super(nil)
self.site_id ||= site_id
end
I instanciate the object via the Rails console like this:
r = Resource.new(100)
Is the has_attachment method running before my initialize method? How can I pass a parameter into the :path_prefix dynamically when the model is instantiated?
site_id is a dynamic value, so you can't set this in the class. You'll want to redefine #full_filename in your model. The current definition looks like:
def full_filename(thumbnail = nil)
file_system_path = (thumbnail ? thumbnail_class : self).attachment_options[:path_prefix].to_s
File.join(RAILS_ROOT, file_system_path, *partitioned_path(thumbnail_name_for(thumbnail)))
end
Change the final line to something like:
File.join(RAILS_ROOT, file_system_path, site_id.to_s, *partitioned_path(thumbnail_name_for(thumbnail)))
Related
I have a Notifications module which have classes like 1)car 2)bike 3)Aeroplane. I have a serialized column in UserFeature model.And I have a module 'Notifications' which has list of 11 classes in it.
Notifications
1)car
2)bike
3)Aeroplane
The hash structure of the column notifications in UserFeature model must be
{:car => {:mirror => :true, :door => :true}
:bike => {:x=> :true, :x => :true}
:Aeroplane => {:p => :true, :q => :true}
}
I can access user_object.Notifications
But so as to access user_object.car and also user_object.mirror I need to write getter/setter methods { Defining getter/setter dynamically because I dont want to write getter/setter for every method and also I am unsure about the number of methods I have -> which in future may extend }
Notifications.constants.each do |notification_class|
class_methods = "Notifications::#{notification_class}".constantize.methods(false)
class_methods.each do |method|
method_name = method[0..-4].split('(')[0]
setter_getter_name = "#{notification_class.to_s.underscore}_#{method_name}"
define_method("#{setter_getter_name}=") do |value|
self.notifications = GlobalUtils.form_hash(self.notifications, "#{notification_class}".to_sym, "#{method_name}".to_sym)
self[:notifications]["#{notification_class}".to_sym][ "#{method_name}".to_sym] = value
end
define_method("#{setter_getter_name}") do
self.notifications.fetch("#{notification_class_name}".to_sym, {}).fetch("#{method_name}".to_sym)
end
end
end
But still when i try to access user_object.mirror,
undefined method for #<UserFeature000043645345>
What I am doing wrong?
I need to do this using getter/setter method only
An OpenStruct is a data structure, similar to a Hash, that allows the definition of arbitrary attributes with their accompanying values. This is accomplished by using Ruby’s metaprogramming to define methods on the class itself.
example:
require 'ostruct'
hash = { "country" => "Australia", :population => 20_000_000 }
data = OpenStruct.new(hash)
p data # -> <OpenStruct country="Australia" population=20000000>
Use Ruby OpenStruct class. It will fulfill your requirements without defining such bunch of code.
Edit1, example:
require 'ostruct'
class Aeroplane < OpenStruct; end
a = Aeroplane.new(:p => :true, :q => :true)
a.p # => true
I have a model which has an image field managed by paperclip:
class Meal < ActiveRecord::Base
has_attached_file :image, :default_url => "/images/normal/missing.png",
:styles => { :medium => "612x612", :small => "300x300" },
:path => ":rails_root/public/system/:attachment/:id/:style/:filename",
:url => "/system/:attachment/:id/:style/:filename"
I can access the different sizes like this:
meals.each do |n|
n.image.url(:small) # gives url for small images
puts n.image.url # returns url for original images, I want this to return small for this function
end
I am rendering the meals in JSON using render :json.
My question is, how can I pass the small image URLs into my meals variable (in my controller below)? I want to be able to return small image URLs as I tried doing above, except return it when my response renders (see below).
UPDATE:
In my controller:
def view_patient
response = Response.new
this_doctor = Doctor.find_by_remember_token(Doctor.digest(auth_params["remember_token"]))
if this_doctor
this_patient = this_doctor.users.find_by_id(params[:id])
if this_patient
meals = this_patient.meals
#
# Here should be code on how to set the meals.image.url to small
glucoses = this_patient.glucoses
response.data = { :patient => this_patient, :meals => meals }
response.code = true
else
response.error = "Could not find patient"
response.code = false
end
else
response.error = "Please Login"
response.code = false
end
render :json => response.json
end
TLDR
# inside meal.rb
def as_json(options=nil)
super( (options || {}).merge({
:methods => [:small_url]
}))
end
def small_url
self.image.url(:small)
end
You can then access the URL in your JSON structure
JSON.parse(meal.to_json)['small_url']
Explanation
When a ActiveModel is serialized through to_json the method as_json is first invoked on the object to separate the actual construction of the JSON data structure from the rendering. This data structure (a hash really) is then encoded as a JSON string through ActiveSupport.
So in orde to customize the object we wish to display as JSON we need to override the as_json method of that object - which is well documented. As per the documentation, the methods key for the options hash simply invokes the methods listed in the array passed as the value (in our case just small_url) and creates a key in the hash to be JSON encoded, with the value of the method invocation.
For an even more detailed explanation, please see this excellent answer.
I am looking to understand how I can access a variable set in method A, then use that variable in method B, and also a clean way of reusing the same part of code and then only changing the query
require 'google/api_client'
module GoogleAnalytics
class Analytic
SERVICE_ACCOUNT_EMAIL_ADDRESS = ENV['SERVICE_ACCOUNT_EMAIL_ADDRESS']
PATH_TO_KEY_FILE = ENV['PATH_TO_KEY_FILE']
PROFILE = ENV['ANALYTICS_PROFILE_ID']
def google_analytics_api
client = Google::APIClient.new(
application_name: "Example Application",
application_version: "1.0")
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/analytics.readonly',
:issuer => SERVICE_ACCOUNT_EMAIL_ADDRESS,
:signing_key => Google::APIClient::KeyUtils.load_from_pkcs12(PATH_TO_KEY_FILE, 'notasecret')).tap { |auth| auth.fetch_access_token! }
api_method = client.discovered_api('analytics','v3').data.ga.get
# make queries
result = client.execute(:api_method => api_method, :parameters => {
'ids' => PROFILE,
'start-date' => Date.new(2014,1,1).to_s,
'end-date' => Date.today.to_s,
'dimensions' => 'ga:pagePath',
'metrics' => 'ga:pageviews',
'filters' => 'ga:pagePath==/'
})
end
end
end
So if i run the method google_analytics_api i get a set of results returned assigned to the variable result.
So what if i want another 2 separate methods that will return different sets of results, so
new users and bounce rates, that would be two separate calls changing the request params wouldnt it? would i have to repeat the whole method?
Is there a way to refactor this so that the authorization call can be wrapped up in its on method and all i change is the request params assigned to result ?
So something like this
def api_call
logic to make request
end
def new_users
api_call
# make queries
result = client.execute(:api_method => api_method, :parameters => {
'ids' => PROFILE,
'start-date' => Date.new(2014,1,1).to_s,
'end-date' => Date.today.to_s,
'dimensions' => 'ga:pagePath',
'metrics' => 'ga:newUsers',
'filters' => 'ga:pagePath==/'
})
end
One of the problems though will be having the local variables client and result available in the new_users method, what could these be changed to? an instance variable with an #? or a class variable with an ## ?
Your instincts are good - you don't want to repeat yourself, and there are better ways of structuring this code. But rather than sharing variables, you should think about small pieces, loosely joined. Write methods that do one thing well, and combine them together. For instance, we could write a get_client method that just returns a client for other methods to use:
protected
def get_client
client = Google::APIClient.new(
application_name: "Example Application",
application_version: "1.0")
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/analytics.readonly',
:issuer => SERVICE_ACCOUNT_EMAIL_ADDRESS,
:signing_key => Google::APIClient::KeyUtils.load_from_pkcs12(PATH_TO_KEY_FILE, 'notasecret')).tap { |auth| auth.fetch_access_token! }
client
end
It's protected because external code - stuff outside your Analytic class - shouldn't work with it directly. They should use the methods we provide for them.
You could also provide a helper method for getting results from the API. I'm not familiar with the query API, but it looks like it's your metrics value that changes. So maybe something like this:
protected
def get_result(metrics)
client = self.get_client
api_method = client.discovered_api('analytics','v3').data.ga.get
result = client.execute(:api_method => api_method, :parameters => {
'ids' => PROFILE,
'start-date' => Date.new(2014,1,1).to_s,
'end-date' => Date.today.to_s,
'dimensions' => 'ga:pagePath',
'metrics' => metrics,
'filters' => 'ga:pagePath==/'
})
result
end
Now you can write simple methods that your external classes can use:
def new_users
get_result('ga:newUsers')
end
def total_visits
get_result('ga:pageViews')
end
If you can, try to return simple data from these methods. Maybe total_visits is going to return get_result('ga:pageViews')['totalsForAllResults']['ga:pageviews'] instead. Code outside your class shouldn't have to know about the GA data format to work with it. This is called encapsulation.
From talking on Skype, I think there are several things to look at
Init
Currently, you're using the google_analytics_api method every time you want to use the module. This is completely inefficient, and is partly why you have this issue now. Instead, I would create an init method, which will fire each time you initialize the object (and make GoogleAnalytics into a class of its own):
#lib/google_analytics.rb
Class GoogleAnalytics
def initialize
... google_analytics_api method here
end
end
This will allow you to treat your current module as a real Ruby object - like this:
#analytics = GoogleAnalytics.new #-> fires initialize method
This will give you the ability to call the object (which will pull the data from the API), and then split that data accordingly, for the different use cases you have.
Instance Methods
This leads me nicely onto the idea of instance methods
What you're referring to, and indeed what Alex P is referring to, is the idea of an instance method. This doubles as an attribute for an object, but essentially allows you to call a piece of functionality on an instance of a method.
So in Alex's example, you have:
def new_users
get_result('ga:newUsers')
end
This is just calling an instance method of your class:
GoogleAnalytics::Analytic.new_users
This will create an instance of the Analytic class, and then call the new_users method (which should be a class method). This method will then allow you to call instance methods on the newly initialized object, hence the get_result method call
--
What I'm proposing is to use instance methods after the object has been initialized, giving you acesss to the data defined with google_analytics_api
For example:
#app/controllers/analyics_controller.rb
Class AnalyticsController < ApplicationController
def index
#analytics = GoogleAnalytics.new
#new_users = #analytics.new_users
end
end
#lib/google_analytics.rb
Class GoogleAnalytics
def initialize
... google_analytics_api method here
end
def new_users
return [new_users_data]
end
end
The one caveat to this is whether this will work without the module. I think it should, but it's untested for me
I use Rails 3.0.6 with mongoID 2.0.2. Recently I encountered an issue with save! method when overriding setter (I am trying to create my own nested attributes).
So here is the model:
class FeedItem
include Mongoid::Document
has_many :audio_refs
def audio_refs=(attributes_array, binding)
attributes_array.each do |attributes|
if attributes[:audio_track][:id]
self.audio_refs.build(:audio_track => AudioTrack.find(attributes[:audio_track][:id]))
elsif attributes[:audio_track][:file]
self.audio_refs.build(:audio_track => AudioTrack.new(:user_id => attributes[:audio_track][:user_id], :file => attributes[:audio_track][:file]))
end
end
if !binding
self.save!
end
end
AudioRef model (which is just buffer between audio_tracks and feed_items) is:
class AudioRef
include Mongoid::Document
belongs_to :feed_item
belongs_to :audio_track
end
And AudioTrack:
class AudioTrack
include Mongoid::Document
has_many :audio_refs
mount_uploader :file, AudioUploader
end
So here is the spec for the FeedItem model which doesn`t work:
it "Should create audio_track and add audio_ref" do
#audio_track = Fabricate(:audio_track, :user_id => #author.id, :file => File.open("#{Rails.root}/spec/stuff/test.mp3"))
#feed_item= FeedItem.new(
:user => #author,
:message => {:body => Faker::Lorem.sentence(4)},
:audio_refs => [
{:audio_track => {:id => #audio_track.id}},
{:audio_track => {:user_id => #author.id, :file => File.open("#{Rails.root}/spec/stuff/test.mp3")}}
]
)
#feed_item.save!
#feed_item.reload
#feed_item.audio_refs.length.should be(2)
end
As you can see, the reason I am overriding audio_refs= method is that FeedItem can be created from existing AudioTracks (when there is params[:audio_track][:id]) or from uploaded file (params[:audio_track][:file]).
The problem is that #feed_item.audio_refs.length == 0 when I run this spec, i.e. audio_refs are not saved. Could you please help me with that?
Some investigation:
1) binding param is "true" by default (this means we are in building mode)
I found a solution to my problem but I didnt understand why save method doesnt work and didn`t make my code work. So first of all let me describe my investigations about the problem. After audio_refs= is called an array of audio_refs is created BUT in any audio_ref is no feed_item_id. Probably it is because the feed_item is not saved by the moment.
So the solution is quite simple - Virtual Attributes. To understand them watch corresponding railscasts
So my solution is to create audio_refs by means of callback "after_save"
I slightly changed my models:
In FeedItem.rb I added
attr_writer :audio_tracks #feed_item operates with audio_tracks array
after_save :assign_audio #method to be called on callback
def assign_audio
if #audio_tracks
#audio_tracks.each do |attributes|
if attributes[:id]
self.audio_refs << AudioRef.new(:audio_track => AudioTrack.find(attributes[:id]))
elsif attributes[:file]
self.audio_refs << AudioRef.new(:audio_track => AudioTrack.new(:user_id => attributes[:user_id], :file => attributes[:file]))
end
end
end
end
And the spec is now:
it "Should create audio_track and add audio_ref" do
#audio_track = Fabricate(:audio_track, :user_id => #author.id, :file => File.open("#{Rails.root}/spec/stuff/test.mp3"))
#feed_item= FeedItem.new(
:user => #author,
:message => {:body => Faker::Lorem.sentence(4)},
:audio_tracks => [
{:id => #audio_track.id},
{:user_id => #author.id, :file => File.open("#{Rails.root}/spec/stuff/test.mp3")}
]
)
#feed_item.save!
#feed_item.reload
#feed_item.audio_refs.length.should be(2)
end
And it works fine!!! Good luck with your coding)
Check that audio_refs=() is actually being called, by adding debug output of some kind. My feeling is that your FeedItem.new() call doesn't use the audio_refs=() setter.
Here's the source code of the ActiveRecord::Base#initialize method, taken from APIdock:
# File activerecord/lib/active_record/base.rb, line 1396
def initialize(attributes = nil)
#attributes = attributes_from_column_definition
#attributes_cache = {}
#new_record = true
#readonly = false
#destroyed = false
#marked_for_destruction = false
#previously_changed = {}
#changed_attributes = {}
ensure_proper_type
populate_with_current_scope_attributes
self.attributes = attributes unless attributes.nil?
result = yield self if block_given?
_run_initialize_callbacks
result
end
I don't currently have an environment to test this, but it looks like it's setting the attributes hash directly without going through each attribute's setter. If that's the case, you'll need to call your setter manually.
Actually, I think the fact you're not getting an exception for the number of arguments (binding not set) proves that your setter isn't being called.
How do I rename a file after is has been uploaded and saved?
My problem is that I need to parse information about the files automatically in order to come up with the file name the file should be saved as with my application, but I can't access the information required to generate the file name till the record for the model has been saved.
If, for example, your model has attribute image:
has_attached_file :image, :styles => { ...... }
By default papepclip files are stored in /system/:attachment/:id/:style/:filename.
So, You can accomplish it by renaming every style and then changing image_file_name column in database.
(record.image.styles.keys+[:original]).each do |style|
path = record.image.path(style)
FileUtils.move(path, File.join(File.dirname(path), new_file_name))
end
record.image_file_name = new_file_name
record.save
Have you checked out paperclip interpolations?
If it is something that you can figure out in the controller (before it gets saved), you can use a combination of the controller, model, and interpolation to solve your problem.
I have this example where I want to name a file based on it's MD5 hash.
In my controller I have:
params[:upload][:md5] = Digest::MD5.file(file.path).hexdigest
I then have a config/initializers/paperclip.rb with:
Paperclip.interpolates :md5 do|attachment,style|
attachment.instance.md5
end
Finally, in my model I have:
validates_attachment_presence :upload
has_attached_file :upload,
:path => ':rails_root/public/files/:md5.:extension',
:url => '/files/:md5.:extension'
To add to #Voyta's answer, if you're using S3 with paperclip:
(record.image.styles.keys+[:original]).each do |style|
AWS::S3::S3Object.move_to record.image.path(style), new_file_path, record.image.bucket_name
end
record.update_attribute(:image_file_name, new_file_name)
My avatar images are named with the user slug, if they change their names I have to rename images too.
That's how I rename my avatar images using S3 and paperclip.
class User < ActiveRecord::Base
after_update :rename_attached_files_if_needed
has_attached_file :avatar_image,
:storage => :s3,
:s3_credentials => "#{Rails.root}/config/s3.yml",
:path => "/users/:id/:style/:slug.:extension",
:default_url => "/images/users_default.gif",
:styles => { mini: "50x50>", normal: "100x100>", bigger: "150x150>" }
def slug
return name.parameterize if name
"unknown"
end
def rename_attached_files_if_needed
return if !name_changed? || avatar_image_updated_at_changed?
(avatar_image.styles.keys+[:original]).each do |style|
extension = Paperclip::Interpolations.extension(self.avatar_image, style)
old_path = "users/#{id}/#{style}/#{name_was.parameterize}#{extension}"
new_path = "users/#{id}/#{style}/#{name.parameterize}#{extension}"
avatar_image.s3_bucket.objects[old_path].move_to new_path, acl: :public_read
end
end
end
And to add yet another answer, here is the full method I'm using for S3 renaming :
def rename(key, new_name)
file_name = (key.to_s+"_file_name").to_sym
old_name = self.send(file_name)
(self.send(key).styles.keys+[:original]).each do |style|
path = self.send(key).path(style)
self[file_name] = new_name
new_path = self.send(key).path(style)
new_path[0] = ""
self[file_name] = old_name
old_obj = self.send(key).s3_object(style.to_sym)
new_obj = old_obj.move_to(new_path)
end
self.update_attribute(file_name, new_name)
end
To use : Model.find(#).rename(:avatar, "test.jpg")
I'd like to donate my "safe move" solution that doesn't rely on any private API and protects against data loss due to network failure:
First, we get the old and new paths for every style:
styles = file.styles.keys+[:original]
old_style2key = Hash[ styles.collect{|s| [s,file.path(s).sub(%r{\A/},'')]} ]
self.file_file_name = new_filename
new_style2key = Hash[ styles.collect{|s| [s,file.path(s).sub(%r{\A/},'')]} ]
Then, we copy every file to it's new path. Since the default path includes both object ID and filename, this can never collide with the path for a different file. But this will fail if we try to rename without changing the name:
styles.each do |style|
raise "same key" if old_style2key[style] == new_style2key[style]
file.s3_bucket.objects[old_style2key[style]].copy_to(new_style2key[style])
end
Now we apply the updated model to the DB:
save!
It is important to do this after we create the new S3 objects but before we delete the old S3 objects. Most of the other solutions in this thread can lead to a loss of data if the database update fails (e.g. network split with bad timing), because then the file would be at a new S3 location but the DB still points to the old location. That's why my solution doesn't delete the old S3 objects until after the DB update succeeded:
styles.each do |style|
file.s3_bucket.objects[old_style2key[style]].delete
end
Just like with the copy, there's no chance that we accidentally delete another database object's data, because the object ID is included in the path. So unless you rename the same database object A->B and B->A at the same time (e.g. 2 threads), this delete will always be safe.
To add to #Fotios's answer:
its the best way I think to make custom file name, but in case you want file name based on md5 you can use fingerprint which is already available in Paperclip.
All you have to do is to put this to config/initializers/paperclip_defaults.rb
Paperclip::Attachment.default_options.update({
# :url=>"/system/:class/:attachment/:id_partition/:style/:filename"
:url=>"/system/:class/:attachment/:style/:fingerprint.:extension"
})
There's no need to set :path here as by default it's made that way:
:path=>":rails_root/public:url"
I didn't check if it's necessary but in case it doesn't work for you make sure your model is able to save fingerprints in the database -> here
One more tip which I find handy is to use rails console to check how it works:
$ rails c --sandbox
> Paperclip::Attachment.default_options
..
> s = User.create(:avatar => File.open('/foo/bar.jpg', 'rb'))
..
> s.avatar.path
=> "/home/groovy_user/rails_projectes/funky_app/public/system/users/avatars/original/49332b697a83d53d3f3b5bebce7548ea.jpg"
> s.avatar.url
=> "/system/users/avatars/original/49332b697a83d53d3f3b5bebce7548ea.jpg?1387099146"
The following migration solved the problem to me.
Renaming avatar to photo:
class RenamePhotoColumnFromUsers < ActiveRecord::Migration
def up
add_attachment :users, :photo
# Add `avatar` method (from Paperclip) temporarily, because it has been deleted from the model
User.has_attached_file :avatar, styles: { medium: '300x300#', thumb: '100x100#' }
User.validates_attachment_content_type :avatar, content_type: %r{\Aimage\/.*\Z}
# Copy `avatar` attachment to `photo` in S3, then delete `avatar`
User.where.not(avatar_file_name: nil).each do |user|
say "Updating #{user.email}..."
user.update photo: user.avatar
user.update avatar: nil
end
remove_attachment :users, :avatar
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
Hope it helps :)
Another option is set to default, work for all upload.
This example change name file to 'name default' for web, example: test áé.jpg to test_ae.jpg
helper/application_helper.rb
def sanitize_filename(filename)
fn = filename.split /(?<=.)\.(?=[^.])(?!.*\.[^.])/m
fn[0] = fn[0].parameterize
return fn.join '.'
end
Create config/initializers/paperclip_defaults.rb
include ApplicationHelper
Paperclip::Attachment.default_options.update({
:path => ":rails_root/public/system/:class/:attachment/:id/:style/:parameterize_file_name",
:url => "/system/:class/:attachment/:id/:style/:parameterize_file_name",
})
Paperclip.interpolates :parameterize_file_name do |attachment, style|
sanitize_filename(attachment.original_filename)
end
Need restart, after put this code