Category Archives: Rails3

[Paperclip]Attach non-image files in Rails3

ref. Attach Non Image Files in Rails With Paperclip:
http://practiceovertheory.com/blog/2009/05/19/attach-non-image-files-in-rails-with-paperclip/

이미지가 아닌 문서 파일을 업로드할 경우 Paperclip gem 패키지에서 에러가 발생함.
before_post_process 메소드를 이용해 처리한다.

class Attachment < ActiveRecord::Base
  attr_accessible :asset
  #paperclip: file attachments
  has_attached_file :asset, :styles => { :medium => "300x300>", :thumb => "100x100>" }, 
                     :default_url => "/images/:style/missing.png",
                     #:url => "/system/:class/:attachment/:id_partition/:style/:filename",
                     #:url => "/system/:class/:attachment/:id/:style_:hash.:extension",
                     #:hash_secret => "rmdwjddmlgla"
                     :url => "/system/:class/:attachment/:id/:style/:updated_at.:extension"

  validates :asset, :attachment_presence => true
  before_post_process :image?
  
  def image?
    !(asset_content_type =~ /^image.*/).nil?
  end
  
end

[Rails3]How to set blank date on jquery datepicker in rails

TypeError: Object [object Object] has no method ‘Datepicker’

ref. http://rubydoc.info/gems/jquery-rails/2.0.2/frames

== Append ‘//=require jquery-ui’ to application.js:

vi app/assets/javascripts/application.js

//= require jquery
//= require jquery_ujs
//= require_tree
//= require jquery-ui

== Set jQuery datepicker option ‘showOn’ to ‘button’ -> “datepicker({showOn:’button’})”

vi app/views/new.html.erb

<%= form_for(@wash) do |f| %>

<%#= f.date_select :stocked_on %>
<%= f.text_field :stocked_on, :size =>10 %>

<%= f.submit %>
<% end %>

<script type=”text/javascript”>
jQuery.noConflict();
jQuery(document).ready(function($){
$(“#wash_stocked_on”).datepicker({showOn:’button’});
});
</script>

[ruby on rails] install gem rmagick in ubuntu

ref. http://expressica.com/2007/07/04/how-to-install-rmagick-gem-on-linuxubuntu/

sudo apt-get install imagemagick
sudo apt-get install libmagick9-dev
sudo gem install rmagick

—– ERROR ———-
$ gem install rmagick

Building native extensions. This could take a while…
ERROR: Error installing rmagick:
ERROR: Failed to build gem native extension.

/home/jinny/.rvm/rubies/ruby-1.9.3-p125/bin/ruby extconf.rb
checking for Ruby version >= 1.8.5… yes
extconf.rb:128: Use RbConfig instead of obsolete and deprecated Config.
checking for gcc… yes
checking for Magick-config… no
Can’t install RMagick 2.13.1. Can’t find Magick-config

[Ruby on Rails] escape pre code <, >


class Regexp
	def each_match(str)
	     	#start = 0
		text =""
	   	#while matchdata = self.match(str, start)
	   	while match_data = self.match(str)
	   		text << match_data.pre_match	
		     	yield text, match_data
		      	#start = matchdata.end(0)
		      	str = match_data.post_match
		end
		text << str
	end
end

module ApplicationHelper
# In Ruby 1.9, you can also associate a block with a call to match. If no match is found,
# the block is ignored, and match returns nil. If a match is found, however, the
# MatchData object is passed to the block, and the match method returns whatever the
# block returns.

	def escape_precode(stprivater)
		return  if str.empty?
		pattern = %r{(<pre\s*[^>]*>)(\s*)(<code\s*[^>]*>)?(.*?)(</code>)?(\s*)(</pre>)}im
		return pattern.each_match(str) do |text,match_data| 
			if match_data.length == 8 
				text << handle_match8(match_data)
			elsif match_data.length == 6
				text << thandle_match6(match_data)
			end
		end	
	end

	protected
	def handle_match6(match_data)
		#return  "" if match_data.nil? or match_data.length != 6
		rt = "#{match_data[1]}#{match_data[2]}"
		rt << match_data[3].gsub(/</,'<').gsub(/>/,'>')
		rt << "#{match_data[4]}#{match_data[5]}"
	end

	def handle_match8(match_data)
		rt = "#{match_data[1]}#{match_data[2]}#{match_data[3]}"
		rt << match_data[4].gsub(/</,'<').gsub(/>/,'>')
		#rt << begin match_data[4].gsub!(/</,'<').gsub!(/>/,'>'); rescue  => ex;ex.message; end
		rt << "#{match_data[5]}#{match_data[6]}#{match_data[7]}"
	end
end
	

text3 = <<code>

<div id="list">
  <div>
    <%= @commentable.title %>
  </div>
  <div style="line-height:2.2em">
    <%=sanitize escape_precode @commentable.body %>
  </div>

  <h3>Listing comments</h3>
  <% @root_comments.each do |root| %>
    <% Comment.each_with_level( root.self_and_descendants) do |comment, level| %>
        <%= ('<div class="prefix_1">' * level).html_safe %>
        <hr/><%= comment.id %>:<%= comment.parent_id %>
        <div style="line-height:2.2em"> <%= begin sanitize(escape_precode( comment.body)) rescue  comment.body  end%>
        </div>
      <div>  
        <spen><%= comment.created_at %></spen>
        <spen>by <%= comment.user.email %></spen>
         <spen><%= link_to 'Reply', post_comment_path(@commentable,comment) %></spen>
       <spen><%= link_to 'Edit', edit_post_comment_path(@commentable,comment) %></spen>
        <spen><%= link_to 'Destroy', post_comment_path(@commentable, comment), confirm: 'Are you sure?', method: :delete %></spen>
      </div>
     <%= ('</div>' * level).html_safe %> 
    <% end %>
  <% end %>

  <br />
  <h2>New Comment</h2>  
  <%= form_for [@commentable, Comment.new] do |f| %>  
    <div>  
        <%= f.label :body %> <br/> 
        <%= f.text_area :body, rows: 12, cols: 68  %>  
      </div>  
      <div><%= submit_tag "Add Comment" %>   <%= link_to t('Back'), you_posts_path %></div>  
   <% end %>  
 
</code></pre>
<pre>
<%= form_for(@post) do |f| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
      <% @post.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
</pre>
EOT

include ApplicationHelper
puts Time.now
puts escape_precode(text3)
puts Time.now

[ruby on rails] declative_authorization 함수들

ref. http://www.tzi.org/~sbartsch/declarative_authorization/master/

Module Authorization::AuthorizationHelper
In: lib/declarative_authorization/helper.rb
Methods

has_any_role?   has_any_role_with_hierarchy?   has_role?   has_role_with_hierarchy?   permitted_to?  

permitted_to?(privilege, object_or_sym = nil, options = {}, &block)

If the current user meets the given privilege, permitted_to? returns true and yields to the optional block. The attribute checks that are defined in the authorization rules are only evaluated if an object is given for context.

Examples:

    <% permitted_to? :create, :users do %>
    <%= link_to 'New', new_user_path %>
    <% end %>
    ...
    <% if permitted_to? :create, :users %>
    <%= link_to 'New', new_user_path %>
    <% else %>
    You are not allowed to create new users!
    <% end %>
    ...
    <% for user in @users %>
    <%= link_to 'Edit', edit_user_path(user) if permitted_to? :update, user %>
    <% end %>
To pass in an object and override the context, you can use the optional options:

    permitted_to? :update, user, :context => :account

has_role?(*roles, &block)
While permitted_to? is used for authorization in views, in some cases content should only be shown to some users without being concerned with authorization. E.g. to only show the most relevant menu options to a certain group of users. That is what has_role? should be used for.

Examples:

    <% has_role?(:sales) do %>
    <%= link_to 'All contacts', contacts_path %>
    <% end %>
    ...
    <% if has_role?(:sales) %>
    <%= link_to 'Customer contacts', contacts_path %>
    <% else %>
    ...
    <% end %>

Module Authorization::AuthorizationInModel
In: lib/declarative_authorization/in_model.rb
Methods

after_find   obligation_scope_for   permitted_to!   permitted_to?   using_access_control   using_access_control?   using_access_control?   with_permissions_to 

Public Class methods:

using_access_control(options = {})

Activates model security for the current model. Then, CRUD operations are checked against the authorization of the current user. The privileges are :create, :read, :update and :delete in the context of the model. By default, :read is not checked because of performance impacts, especially with large result sets.

  class User < ActiveRecord::Base
    using_access_control
  end
If an operation is not permitted, a Authorization::AuthorizationError is raised.

To activate model security on all models, call using_access_control on ActiveRecord::Base

  ActiveRecord::Base.using_access_control
Available options

:context - 
Specify context different from the models table name.
:include_read - 
Also check for :read privilege after find.

[ruby on rails] rails 3 application.rb: invalid multibyte char (US-ASCII) (SyntaxError)

ref. http://stackoverflow.com/questions/4717717/invalid-multibyte-char-us-ascii-validating-a-new-user-with-regex-using-ruby

When using UTF-8 and Ruby 1.9 you’ll need to prefix your files by adding as the first line:

# encoding: UTF-8

This is a hint to the parser to make sure not to interpret things using the wrong character set. Ruby 1.8 was really lax about this and it could cause trouble.

[Javascript] Rails-like number_with_delimiter in javascript

ref. http://kevinvaldek.posterous.com/number-with-delimiter-in-javascript
- http://sleeplesscoding.blogspot.com/2011/02/rails-like-numberwithdelimiter-in.html

function number_with_delimiter(number, delimiter) {
  number = number + '', delimiter = delimiter || ',';
  var split = number.split('.');
  split[0] = split[0].replace(/(d)(?=(ddd)+(?!d))/g, '$1' + delimiter);
  return split.join('.');
};
var num = 12345678;  
var str = num.number_with_delimiter();  
alert(str); 
Number.prototype.number_with_delimiter = function(delimiter) {
    var number = this + '', delimiter = delimiter || ',';
    var split = number.split('.');
    split[0] = split[0].replace(
        /(d)(?=(ddd)+(?!d))/g,
        '$1' + delimiter
    );
    return split.join('.');    
};
number_with_delimiter(12345678)
> 12,345,678

number_with_delimiter(12345678, ':')
> 12:345:678

number_with_delimiter(12345678.555)
> 12,345,678.555

[rails] f.date_select can’t convert Symbol into String

ref. http://stackoverflow.com/questions/1386244/problem-in-rails-scaffold-for-date-fields

- download standard translation files: https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale

This is highly likely to be caused by localization. You have entered a different standard locale than :en (in application.rb or environment.rb), but you have not declared the appropriate translations for month names, causing rails to balk.

[RubyGem] Update RubyGem itself

Update error of RubyGem:
NOTE: RubyGems 1.5.0 and 1.5.1 have a broken gem update –system.

$ gem update --system
Updating RubyGems
ERROR:  While executing gem ... (NoMethodError)
    undefined method `version' for nil:NilClass

To upgrade from rubygem 1.5.0, 1.5.1:
rubygem 1.5.0,1.5.1 을 최신버전으로 업그레이드 하는 방법

$ gem install rubygems-update
$ update_rubygems

To upgrade from rubygem < 1.5.0:
rubygem 버전< 1.5.0 이하에서 업그레이드 하기

$ gem update --system