Rails 3, windows, Paperclip can't make thumbnails - windows

So I am using windows 7, Rails 3, latest paperclip gem and ImageMagick-6.7.7-Q16 (tested in cmd), my PATH environment is updated.
Model
class Image < ActiveRecord::Base
attr_accessible :description, :user_id, :file
has_attached_file :file, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :storage => :filesystem
belongs_to :user
#validations
validates_attachment_presence :file
validates_attachment_size :file, :less_than => 4.megabytes
validates_attachment_content_type :file, :content_type => [ 'image/gif', 'image/png', 'image/x-png', 'image/jpeg', 'image/pjpeg', 'image/jpg' ]
end
Form
<%= form_for(#image, :html => { :multipart => true }) do |image| %>
<div class="control-group">
<%= image.label :description, "Description", :class => 'control-label' %>
<div class="controls">
<div class="input-prepend">
<%= image.text_field :description %>
</div>
</div>
</div>
<div class="control-group">
<%= image.label :file, "Image", :class => 'control-label' %>
<div class="controls">
<div class="input-prepend">
<%= image.file_field :file %>
</div>
</div>
</div>
<%= image.hidden_field :user_id, :value => current_user.id %>
<div class="actions">
<%= image.submit "Upload Image", :class => 'btn btn-primary btn-medium' %>
</div>
<% end %>
My paperclip.rb in initializers
require "paperclip"
Paperclip.options[:command_path] = 'C:\Program Files (x86)\ImageMagick-6.7.7-Q16'
Paperclip.options[:swallow_stderr] = false
Paperclip.options[:whiny_thumbnails] = true
Everything is working fine without cropping (:styles => { :medium => "300x300>", :thumb => "100x100>" }). But when I want to make thumbnails Paperclip throws this error
Command :: identify -format %wx%h "C:/Users/Zaraka/AppData/Local/Temp/DSCN630520120519-7696-18l3nw5.JPG[0]"
Command :: convert "C:/Users/Zaraka/AppData/Local/Temp/DSCN630520120519-7696-18l3nw5.JPG[0]" -resize "300x300>" "C:/Users/Zaraka/AppData/Local/Temp/DSCN630520120519-7696-18l3nw520120519-7696-1p8rcsr"
[paperclip] An error was received while processing: #<Paperclip::Error: There was an error processing the thumbnail for DSCN630520120519-7696-18l3nw5>
Command :: identify -format %wx%h "C:/Users/Zaraka/AppData/Local/Temp/DSCN630520120519-7696-18l3nw5.JPG[0]"
Command :: convert "C:/Users/Zaraka/AppData/Local/Temp/DSCN630520120519-7696-18l3nw5.JPG[0]" -resize "100x100>" "C:/Users/Zaraka/AppData/Local/Temp/DSCN630520120519-7696-18l3nw520120519-7696-tx3bmo"
[paperclip] An error was received while processing: #<Paperclip::Error: There was an error processing the thumbnail for DSCN630520120519-7696-18l3nw5>
I figured out that uploaded image isn't even in temp folder, so those created images just have 0 bytes. I'm completely stuck here dunno if something wrong is with paperclip or image upload.
Any help will be appreciated

This probably means you're not pointing to IM properly. Either you don't have it installed yet or just not finding it as expected. Use double backslashes instead: 'C:\\Program Files (x86)\\ImageMagick-6.7.7-Q16'. (In order to avoid white spaces you can also use 8.3 filenames system to identify the path with regular slashes.)
If you're using the last version of Paperclip (3.1.4), on Windows I recommend you to install File package from GnuWin32. Please see this post: https://github.com/thoughtbot/paperclip/issues/926.
Finally, in order to support non-English characters in filenames, you might want to monkey patch Cocaine. I put a cocaine_path.rb between my initializers. Be aware that 'iso-8859-1' might not be the proper encoding for you.
cocaine_pacth.rb:
if RUBY_PLATFORM == "i386-mingw32"
module Cocaine
class CommandLine
def run
output = ''
begin
with_modified_path do
#logger.info("\e[32mCommand\e[0m :: #{command}") if #logger
ec = Encoding::Converter.new("utf-8", "iso-8859-1")
output = self.class.send(:'`', ec.convert(command.encode('UTF-8')))
end
rescue Errno::ENOENT
raise Cocaine::CommandNotFoundError
end
if $?.exitstatus == 127
raise Cocaine::CommandNotFoundError
end
unless #expected_outcodes.include?($?.exitstatus)
raise Cocaine::ExitStatusError, "Command '#{command}' returned #{$?.exitstatus}. Expected #{#expected_outcodes.join(", ")}"
end
output
end
end
end
end
This covers all the issues I have had with Paperclip on Windows in the last days. I hope it helps.

Related

upload image and files padrino

i want to put index image to my blog's posts
and have an upload form in 'new post 'in admin's panel
the form is written like this :
- error = #post.errors.include?(:file)
%fieldset.control-group{:class => error ? 'has-error' : ''}
=f.label :file, :class => 'control-label'
.controls
=f.file_field :file ,:name => 'file'
- error = #post.errors.include?(:title)
%fieldset.control-group{:class => error ? 'has-error' : ''}
=f.label :title, :class => 'control-label'
.controls
=f.text_field :title, :class => 'form-control input-large input-with-feedback', :autofocus => true
%span.help-inline=error ? f.error_message_on(:title, :class => 'text-error') : pat(:example)
- error = #post.errors.include?(:body)
%fieldset.control-group{:class => error ? 'has-error' : ''}
=f.label :body, :class => 'control-label'
.controls
~f.text_area :body, :class => 'form-control input-large input-with-feedback'
%span.help-inline=error ? f.error_message_on(:body, :class => 'text-error') : pat(:example)
.form-actions
=f.submit pat(:save), :class => 'btn btn-primary'
=f.submit pat(:save_and_continue), :class => 'btn btn-info', :name => 'save_and_continue'
=link_to pat(:cancel), url(:posts, :index), :class => 'btn btn-default'
but i don't know what i must do in functions to save file .
An easy-to-follow guide (assuming you are using activerecord. otherwise change 1st line on example).
Add carrierwave to your Gemfile, and execute bundle install.
Generate a migration: padrino g AddImageToPosts image:string and execute it.
Add mount_uploader :image, Uploader to your Post model.
Inside your lib folder create a file, named uploader.rb (or whatever, but then do not forget to change Uploader on 3rd step.)
Add lines from 7 to 83 to uploader.rb (do not forget uncomment lines, and fix them so they to match your needs).
Browse admin, click browse button for file upload - select a file from filesystem - you are done.
example (step 3)
require 'carrierwave/orm/activerecord'
class Post < ActiveRecord::Base
belongs_to :category
mount_uploader :image, Uploader
...
end

Rendering a partial with locals

I've rendered a partial that also loads the Users latest post in one of the tab panels.
<div role="tabpanel" class="tab-pane" id="updates_panel">
<%= render :partial => "pages/update_panel", :locals => { :post => #user.latest_post } %>
</div>
At first the method latest_post was to display the users "Last or Latest Post".
def latest_post
posts.order(:created_at => :desc).first
end
But now I realized I need to display all the post in descending order and I cant seem to get this right.
create another method like latest_posts,
def latest_posts
posts.order(:created_at => :desc)
end
def latest_post
latest_posts.first
end
And now use this in your partal,
<%= render :partial => "pages/update_panel", :locals => { :post => #user.latest_post, :posts => #user.latest_posts } %>

How do I output a multidimensional hash in ERB files?

I need some help printing the values of my hash. In my "web.rb" file I have:
class Main < Sinatra::Base
j = {}
j['Cordovan Communication'] = {:title => 'UX Lead', :className => 'cordovan', :images => ['http://placehold.it/350x150','http://placehold.it/350x150','http://placehold.it/350x150']}
j['Telia'] = {:title => 'Creative Director', :className => 'telia', :images => ['http://placehold.it/350x150','http://placehold.it/350x150','http://placehold.it/350x150','http://placehold.it/350x150']}
get '/' do
#jobs = j
erb :welcome
end
end
In "welcome.rb" I'm printing the values of the hash, but it doesn't work:
<% #jobs.each do |job| %>
<div class="row">
<div class="span12">
<h2><%=h job.title %></h2>
</div>
</div>
<% end %>
Here's my error message:
NoMethodError at / undefined method `title' for #<Array:0x10c144da0>
Think what #jobs looks like:
#jobs = {
'Cordovan Communication' => {
:title => 'UX Lead',
:className => 'cordovan',
:images => ['http://placehold.it/350x150','http://placehold.it/350x150','http://placehold.it/350x150']},
'Telia' => {
:title => 'Creative Director',
:className => 'telia',
:images => ['http://placehold.it/350x150','http://placehold.it/350x150','http://placehold.it/350x150','http://placehold.it/350x150']}
}
Then remember that each called on a hash passes a key and a value to the block, and you'll see that you have:
#jobs.each do |name, details|
# On first step, name = 'Cordovan Communication', details = {:title => 'UX Lead', ...}
end
So what you want is probably:
<% #jobs.each do |name, details| %>
<div class="row">
<div class="span12">
<h2><%=h details[:title] %></h2>
</div>
</div>
<% end %>
There's no automatic method creation for Ruby hashes, e.g., you can't call job.title, since there is no title method on Hash objects. Instead you can call job[:title].
Also note that #jobs is a hash, not an array, so you probably want to call #jobs.each_pair rather than #jobs.each. It's possible to use #jobs.each, but in this case it's not going to give you what you expect.

How to write a custom SimpleForm Builder to replace <INPUT> by <P>?

Extract of my Gemfile:
gem 'rails', '3.0.3'
gem 'inherited_resources', '1.2.1'
gem 'simple_form', '1.4.0'
For any resource, I have 1 view for the 3 actions (new, edit & show). Example:
<h1><%= I18n.t('admin.form.'+action_name.downcase, :name => controller_friendly_name) %></h1>
<%= simple_form_for([:admin, resource]) do |f| %>
<%= render "admin/shared/errors" %>
<%= f.input :title,
:label => "Title",
:hint => I18n.t('admin.form.input.title.hint', :name => controller_friendly_name),
:required => true,
:error => false,
:input_html => { :class => :large, :placeholder => I18n.t('admin.form.input.title.placeholder', :name => controller_friendly_name) }
%>
<%= f.input :is_visible,
:as => :radio,
:label => "Visible",
:error => false,
:required => true,
:collection => [['Yes', true], ['No', false]],
:wrapper_class => 'checkboxes-and-radiobuttons',
:checked => true
%>
<%= render "admin/shared/validation", :f => f %>
<% end %>
<% init_javascript "MyApplication.Form.disable();" if [:show].include?(action_name.to_sym) %>
See how the #show action set all the fields to disabled ? This is ugly.
Consider I can't refactor the views to have a show.html.erb file.
What I want to do:
When the action is #show, the simple_form builder use a custom builder wich replace <input>, <textarea>, <select> by <p> html tag, with the value.
Furthermore, I will customise the radiobuttons, checkboxes to.
My first step:
# app/inputs/showvalue_input.rb
class ShowvalueInput < SimpleForm::Inputs::Base
def input
# how to change 'text_field' by <p> container ?
#builder.text_field(attribute_name, input_html_options)
end
end
Can't find the way to do it. Custom Form Builders or Custom Inputs (with monkey patching) ?
Thank for the help !
Here's my solution
in my application_helper.rb:
def set_show_method_to_builder(builder)
builder.instance_eval <<-EVAL
def show?
#{action_name == "show"}
end
EVAL
end
In my forms (in the simple_form block):
<%- set_show_method_to_builder(f) -%>
And finally, in #app/inputs/string_input.rb:
class StringInput < SimpleForm::Inputs::StringInput
def input
if #builder.show?
content_tag(:p, #builder.object[attribute_name], :class => :show)
else
super
end
end
end
There's some problem with data types not mapped, but it's another story:
Can't create Custom inputs for some (Text, Booleans, ...) types, with SimpleForm

How do I add validation to a partial in Rails 3?

This is the error I am getting:
ArgumentError in Home#index
Showing /app/views/clients/_form.html.erb where line #6 raised:
You need to supply at least one validation
Extracted source (around line #6):
3: render :partial => "clients/form",
4: :locals => {:client => client}
5: -%>
6: <% client ||= Client.new
7: new_client = client.new_record? %>
8: <%= form_for(client, :html => { :class=>"ajax-form", :id => "client-ajax-form"}, :remote => true, :disable_with => (new_client ? "Adding..." : "Saving...")) do |f| %>
9: <div class="validation-error" style="display:none"></div>
My client model looks like this:
class Client < ActiveRecord::Base
# the user model for the client
belongs_to :user
has_many :projects, :order => 'created_at DESC', :dependent => :destroy
#The following produces the designers for a particular client.
#Get them from the relations where the current user is a client.
has_one :ownership, :dependent => :destroy
has_one :designer, :through => :ownership
validates :name, :presence => true,
:length => {:minimum => 1, :maximum => 128}
validates :number_of_clients
def number_of_clients
Authorization.current_user.clients.count <= Authorization.current_user.plan.num_of_clients
end
end
This is how the app/views/client/_form.html.erb partial looks:
<%#
Edit a single client
render :partial => "clients/form",
:locals => {:client => client}
-%>
<% client ||= Client.new
new_client = client.new_record? %>
<%= form_for(client, :html => { :class=>"ajax-form", :id => "client-ajax-form"}, :remote => true, :disable_with => (new_client ? "Adding..." : "Saving...")) do |f| %>
<div class="validation-error" style="display:none"></div>
<div>
<label for="client_name"><span class="icon name-icon"> </span></label>
<input type="text" class="name" size="20" name="client[name]" id="client_name" value="<%= client.name %>" > <%= f.submit(new_client ? "Add" : "Save", :class=> "green awesome")%>
</div>
<% end %>
<% content_for(:deferred_js) do %>
// From the Client Form
$('#client-ajax-form')
.bind("ajax:success", function(evt, data, status, xhr){
console.log("Calling Step View");
compv.updateStepView('client', xhr);
});
<% end %>
How do I fix that error ?
The problem is caused by the following line in your model:
validates :number_of_clients
When you use validates (s in the end) you have to follow the default rails validations like you did with the name validation. However, when you use a custom method to do the validation, you should use validate instead. So this should work:
validate :number_of_clients

Resources