Ruby on Rails Cheat Sheet


rails 데이터 타입

:string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean

Rails Mimetype   

"./."                      => :all
"text/plain"               => :text
"text/html"                => :html
"application/xhtml+xml"    => :html
"text/javascript"          => :js
"application/javascript"   => :js
"application/x-javascript" => :js
"text/calendar"            => :ics  
"text/csv"                 => :csv  
"application/xml"          => :xml
"text/xml"                 => :xml
"application/x-xml"        => :xml
"text/yaml"                => :yaml
"application/x-yaml"       => :yaml
"application/rss+xml"      => :rss  
"application/atom+xml"     => :atom 
"application/json"         => :json
"text/x-json"              => :json

bundle asset precompile

bundle exec rake assets:precompile RAILS_ENV="production"
rake assets:clean< add below code if you want development environment with out precompile config.serve.static.assets = false application.rb use Bundler.require(:default, :assets, Rails.env) instead of Bundler.require(*Rails.groups(:assets => %w(development test)))

compile assets locally

Put below into development.rb
config.assets.prefix = "/temp-assets"
Also put below into application.rb
config.assets.initialize.on.precompile = false

rails logger

Rails.logger.info "My info message"
Rails.logger.debug "My debugging message"
Rails.logger.warn "My warning message"

Environment Log level

config.log_level = :debug, :info, :warn, :error, and :fatal

Validation text length CR filter

before.validation :replace.cr
  protected
  def replace.cr
    if self.description.changed?
      self.description.gsub!(/\r\n?/, "\n")
    end
  end

validation locale


// config/locales/en.yml
en:
  activerecord:
    attributes:
      user:
        email: "E-mail address"
    errors:
      models:
        user:
          attributes:
            email:
              blank: "is required"
If you are using mongoid, replace activerecord: with mongoid:

Validate associated

The answer to this turned out to be rather simple. On the parent model, you simply explicitly declare that you want the associated children validated.
parent.rb
validates_associated :children

Validate if persisted? or new_record?

validates.uniqueness.of :nickname, :message => I18n.t("user.already.taken"), :if => :new.record?
validates.uniqueness.of :nickname, :message => I18n.t("user.already_taken"), :unless => :persisted?

Session Store in rails 3

Use the database for sessions instead of the cookie-based default, which shouldn't be used to store highly confidential information
Create the session table with
rake db:sessions:create
Run the migration
rake db:migrate
Make sure you also tell rails to use ActiveRecord to manage your sessions too.
Rails 3
config/initializers/session.store.rb:
Rails.application.config.session.store :active.record.store

DB Migrate Production

rake db:migrate RAILS_ENV="production"

get rails environment

Rails.env
env["SERVER_NAME"]

rails template

rake print --silent RECIPES=jquery,haml,rspec,cucumber,guard,mongoid,action.mailer,devise,add.user,home.page,home.page.users,seed.database,users.page,css.setup,application.layout,html5,navigation,cleanup,ban.spiders,extras,git,compass,omniauth,omniauth.email,backbone > ~/Desktop/backbone.template.txt
Could you please run it again using the "-T -O -J" flags? As in
rails new template_test -m https://github.com/fortuity/rails3-application-templates/raw/master/rails3-mongoid-devise-template.rb -T -O -J
http://blog.dominicsayers.com/2011/08/16/howto-use-a-rails-template-from-github-on-windows/

thin start

D:\dev\ruby192\bin\ruby.exe -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) D:/dev/workspace/baksisi/script/rails server thin -b 127.0.0.1 -p 3002 -e development
ruby ./script/rails server thin -b smoke-free-online.de -p 3000 -e development -d
thin start

Middle Man

"server" was called incorrectly. Call as "middleman server [-p 4567] [-e development]".
"middleman server [-p 4567] [-e development]" instead of "middleman server -p 4567 -e development

DB migration

Rails g migration change.data.type.for.table_column

I18n

locale join

config/application.rb
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '.*', '..{rb,yml}')]

locale path

routes.rb
  match '/:locale' => "home#index"
  root :to => "home#index"
  scope "/:locale" do   
    controller :models do
      something
    end
    resources :models, :only => :show
ApplicationController
  def default.url.options(options = {})
    options.merge!({:locale => I18n.locale})
  end   

Localize

I18n.l Time.now, :format => :short,  :locale => :"ko"

Pluralization

ko:
  pears:
    zero: ko.zero
    one: ko.one
    few: ko.few
    other: ko.other

generate rake tasks

rails g task namespace task1 task2
rake -T | grep namespace

세션 저장

config.session.store :cookie.store, :key => '.baksisi.session', :domain => :all
environment.rb 메일러에 레이아웃을 지정하고 싶다면.
DeviseMailer.layout "OMG"

show routes

rake routes

SASS

config/application.rb:
config.generators.stylesheet_engine = :sass
sass-convert style.sass style.scss

Trouble Shootings

uninitialized constant

file name confirm (if file name capital, it can be occurred.)

guard-livereload error

gem install eventmachine --pre 

open-uri.rb file in C:/Ruby1.9.2/lib/ruby/1.9.1/ (of course your path might be different).

http.verify.mode = options[:ssl.verify.mode] || OpenSSL::SSL::VERIFY.NONE

[ERROR] V8 is no longer usable

ulimit -v unlimited  

CSV Data Handling

http://www.ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html

get action information at view

    params[:action]

HAML

rails helper using haml
 
def section(name)
haml.tag(:div, :class => 'section') do
  haml.tag(:h2, name)
  haml.tag(:p, :class => 'section.content') do
    yield
  end
end
end
      
def content.box
  haml.tag :div, :class => "holder" do
    haml.tag :div, :class => "top"
    haml.tag :div, :class => "content" do
      yield
    haml.tag :div, :class => "bottom"
  end
end
and in haml
%html
  %head
  %body
    Maybee some content here.
    - content.box do
      Content that goes in the content_box like news or stuff      
     
fields_for with index
<% @questions.each.with.index do |question,index| %>
    <% f.fields.for :questions, question do |fq| %> 
        # here you have both the 'question' object and the current 'index'
    <% end %>
<% end %>
It’s also possible to specify the instance to be used:
<%= form.for @person do |person.form| %>
...
<% @person.projects.each do |project| %>
  <% if project.active? %>
    <%= person.form.fields.for :projects, project do |project.fields| %>
      Name: <%= project.fields.text_field :name %>
    <% end %>
  <% end %>
<% end %>
<% end %>     

Rails Response

namespace "api" do
  resources :regions, :defaults => { :format => 'xml' }
end
Then you should be able to have the following work for your controller methods:
class Api::RegionsController < ApplicationController
  respond.to :xml, :json
  def index
    respond.with(@regions = Region.all)
  end
end
rescue.from  ActionController::MissingFile do |e|
  # User's browser probably wont display this
  # Content-Type is application/x-shockwave-flash
  render :file => File.join(Rails.public.path, '404.html'), :status => 404
end

show details or stream video

def show
  @media = Media.find params[:id]
  respond.to do |format|
    format.html
    format.flv { send.file @media.path, :disposition => 'inline' }
  end
end
render :file => File.join(Rails.public.path, '404.html'), :status => 404, :content.type => 'text/html'

render with variable

render :partial => "my/conejo", :locals => {:my.val => something}
render "my/liebre", :my.val => something

scope

default_scope order('id DESC')
Model.reorder('')
Model.unscoped

render an other action in the controller, in js.

  render 'result', :id => @item.id, :format => :js
 

layout xhr? 

  class ApplicationController < ActionController::Base
  layout proc{|c| c.request.xhr? ? false : "application" }
  end
  layout :layout.xhr?
  def layout.xhr?
    request.xhr? ? false : 'application'
  end
 

AJAX Performance stale? and touch


 def show
    @list_item = @list.list_items.find( params[ :id ] )
    if stale?( :etag => @list_item, :last_modified => @list_item.updated_at.utc, :public => true )
      respond_with( @list_item )
    end
  end
  Also instead of the update_list method being called from after_save/destroy you can pass :touch => true to the belongs_to association which will do the same

AJAX Handler - ?xhr

respond_with( @something, :layout => !request.xhr? )
or
respond_to do |wants|
  wants.html do
    if request.xhr?
      render :partial => "items"
    else
      render
    end
  end
end

Asset

exist

YourApp::Application.assets.find_asset("#{asset}.file").nil?

### pathname

<YourAppName>::Application.assets.find_asset('Rails.png').pathname

absolute asset_path in view using helper

"#{request.protocol}#{request.host.with.port}#{asset.path('person/gravatar.default.png')}"
"#{request.scheme}://#{request.host.with.port}#{request.script_name}"

Mailer

config

environment/production.rb
  config.action.mailer.default.url.options = {:host => 'localhost:3000',:locale =>I18n.locale}
  config.action.mailer.smtp.settings = {
    :address              => "server.addr",
    :port                 => 587,
    :domain               => "sever.domain",
    :user.name            => "user.name",
    :password             => "user.password",
    :authentication       => "plain",
    :enable.starttls.auto => true
  } 
  config.action.mailer.delivery.method = :smtp
  config.action.mailer.perform.deliveries = true
  config.action.mailer.raise.delivery.errors = false
  config.action.mailer.default :charset => "utf-8"

inline attachement

in mailer

attachments.inline['blank'] = {
    :data => File.read("#{Rails.root.to.s + '/app/assets/images/blank.png'}"),
    :mime.type => "image/png",
    :encoding => "base64"
}

in view

if @offer.image.nil?
  = image.tag( attachments['blank'].url, :id => 'attachement.image', :width => "400", :height => "400")
 

validates in I18n

%{attribute} - field name
%{model} - model name 
%{count} - count


rescue log

begin
  ...some code...
rescue Exception => e
  logger.error e.message
 

Ruby

Iterate

a.each.with.index do |item, index|
  puts item, b[index]
end
array.each.slice(3) do |elements|
  fire.the_event
end

Timezone

in client (js):
function set.time.zone.offset() {
    var current.time = new Date();
    $.cookie('time.zone', current.time.getTimezoneOffset());
}
in Application Controller:
before.filter :set.timezone
def set.timezone 
 min = request.cookies["time.zone"].to_i
 Time.zone = ActiveSupport::TimeZone[-min.minutes]
end

DateTime format

  %a - The abbreviated weekday name (Sun)
&nbsp; %A - The&nbsp; full&nbsp; weekday&nbsp; name (Sunday)
  %b - The abbreviated month name (Jan)
&nbsp; %B - The&nbsp; full&nbsp; month&nbsp; name (January)
  %c - The preferred local date and time representation
  %d - Day of the month (01..31)
  %H - Hour of the day, 24-hour clock (00..23)
  %I - Hour of the day, 12-hour clock (01..12)
  %j - Day of the year (001..366)
  %m - Month of the year (01..12)
  %M - Minute of the hour (00..59)
  %p - Meridian indicator (AM&nbsp; or&nbsp;PM)
  %S - Second of the minute (00..60)
  %U - Week  number  of the current year,
          starting with the first Sunday as the first
          day of the first week (00..53)
  %W - Week  number  of the current year,
          starting with the first Monday as the first
          day of the first week (00..53)
  %w - Day of the week (Sunday is 0, 0..6)
  %x - Preferred representation for the date alone, no time
  %X - Preferred representation for the time alone, no date
  %y - Year without a century (00..99)
  %Y - Year with century
  %Z - Time zone name
  %% - Literal ``%'' character
   t = Time.now
   t.strftime("Printed on %m/%d/%Y")   #=> "Printed on 04/09/2003"
   t.strftime("at %I:%M%p")            #=> "at 08:56AM"
  
   datetime seconds, hours, days, weeks, months, and years
  
    Add below lines to one of your initializer files, e.g., config/environment.rb:
    DateTime::DATE.FORMATS[:short]="short %Y-%m-%d %H:%M:%S"
    Time::DATE.FORMATS[:short] = "short %Y-%m-%d %H:%M:%S"
    Date::DATE.FORMATS[:short] = "short %Y-%m-%d"
    modify view:
    <%= item.create_date.to_s(:short) %>
distance_of_time_in_words(from_time, to_time = 0, include_seconds = false, options = {})
today = DateTime.now
=> #<DateTime: 441799066630193/180000000,-301/1440,2299161>
birthday = Date.new(2008, 4, 10)
=> #<Date: 4909133/2,0,2299161>
days_to_go = birthday - today
time_until = birthday - today
=> Rational(22903369807, 180000000)
time_until.to_i             # get the number of days until my birthday
=> 127
hours,minutes,seconds,frac = Date.day_fraction.to_time(time_until)
[3053, 46, 57, Rational(1057, 180000000)]
- mm  = (now-la    st_cigarette).divmod(Rational(1, 1440))[0]
- past.days = mm / 1440
- past.hours = (mm % 1440) / 60
- past_minutes = mm % 60

timezone

def set_api_time_zone
  utc_offset = current.user.session && current.user.session.user ? current.user.session.user.time.zone.offset.to.i.minutes : 0
  user.timezone = ActiveSupport::TimeZone[utc.offset]
  Time.zone = user.timezone if user.timezone
  Time.zone.today
  Time.now.to.date
    # => Thu, 19 May 2011
  Time.now.in.time.zone('Melbourne').to_date
    # => Fri, 20 May 2011
end

Range step

range.step(2) {|x| puts x}


benchmark

require 'benchmark'
n = 1000000
def answer1 current.subdomain
  case current.subdomain
  when 'www', 'blog', 'foo', 'bar'
  else nil
  end
end
def answer2 current.subdomain
  nil unless  ["www", "blog", "foo", "bar"].include?(current.subdomain)
end
Benchmark.bmbm do |b|
  b.report('answer1'){n.times{answer1('bar')}}
  b.report('answer2'){n.times{answer2('bar')}}
end
Rehearsal -------------------------------------------
answer1   0.290000   0.000000   0.290000 (  0.286367)
answer2   1.170000   0.000000   1.170000 (  1.175492)
---------------------------------- total: 1.460000sec
              user     system      total        real
answer1   0.290000   0.000000   0.290000 (  0.282610)
answer2   1.180000   0.000000   1.180000 (  1.186130)
Benchmark.bmbm do |b|
  b.report('answer1'){n.times{answer1('hello')}}
  b.report('answer2'){n.times{answer2('hello')}}
end
Rehearsal -------------------------------------------
answer1   0.250000   0.000000   0.250000 (  0.252618)
answer2   1.100000   0.000000   1.100000 (  1.091571)
---------------------------------- total: 1.350000sec
              user     system      total        real
answer1   0.250000   0.000000   0.250000 (  0.251833)
answer2   1.090000   0.000000   1.090000 (  1.090418)


출처




by


Tags : , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

Jquery,Coffeescript Snippet 모음


스타일 변화 시키기


    $('HTML').addClass('JS');
    * In your css */
    .JS #myDiv{display:none;}

coffee script 에서 함수 호출


    contents+="<li class='city_candidate' onclick='h(\""+data[v]+"\")'>"+v+"</li>"
    @h = h = (set) ->
      $('span#cityoutput').replaceWith("<span id='cityoutput'>"+set+"</span>")

Ajax Callback


    url = "locations"
    request = $.get url,data
    request.success (data) -> $("#regionresults").html(data)
    request.error (jqXHR, textStatus, errorThrown) -> $("#region
results").append "AJAX Error: ${textStatus}."

Slide UP


jQuery ->
  $(".search input").focus ->
    if @value == "Search"
      @value = ""
      @className = "textinput"  $(".search input").blur ->
    if @value == ""
      @value = "Search"
      @className = "placeholder"
  $('#message').css { border: '1px solid red' }
  $("p").click(function () {
      $(this).slideUp();
    });
    $("p").hover(function () {
      $(this).addClass("hilite");
    }, function () {
      $(this).removeClass("hilite");
    });

Sticky layer


sticky = () ->
  y = $(window).scrollTop()
  if y > $('#topnavigation').height()
    $('#top
navigation').css({
      'position': 'fixed',
      'top': '0',
      'z-index': "4444"
        'width': $('#top_navigation').width(), 'box-shadow': '0px 20px 20px -15px #CCC'
    })
    $('#topnavigation').removeClass("sixteen columns alpha")
    $('#main').css({'padding-top': $('#top
navigation').height()})
  else
    $('#topnavigation').removeAttr('style')
    $('#main').removeAttr('style')
    $('#top
navigation').addClass("sixteen columns alpha")
$(window).scroll(sticky)
$(window).resize(sticky)
   
   

페이드인 메시지


msg = "world"
inv = "you"
show_message = (x,y) ->
  $('span#message').hide().text(x).fadeIn(1000,
  -> $('span#message').append('!')
  )
  $('#hint').hide().text(x).fadeIn(0)$ ->
  showmessage msg,inv
    [inv, msg] = [msg, inv]
 
  $('span#message').click ->
    show
message inv,msg
    [inv, msg] = [msg, inv]
message fadein and out
.fadeIn(30).fadeOut(1000);
   

다이나믹 add remove


$('input#addlanguageskill').on 'click', () ->
  num = ($('.languageskillinnerbox').length)-1
  newNum  = new Number(num+1)
  sourceElem = $('div#language
skill' +num)
  newElem = sourceElem.clone().prop('id','language
skill'+newNum)
  newElem.find("#user
languageskillsattributes"+num+"languageid").prop({id:'userlanguageskillsattributes'+newNum+'languageid',name:'user[languageskillsattributes]['+newNum+'][languageid]'})
  newElem.append('<input onclick="remove(\''+newElem.prop('id')+'\')" id="removelanguageskill"'+newNum+' type="button" value="Remove Language"/>')
  sourceElem.after(newElem)
@remove = remove = (elemid) ->
  alert "remove : "+elem
id
  $("#"+elem_id).remove()

Nested Model Form 예제


<% formfor @person do |personform| %>  <%= personform.label :name %>
  <%= person
form.text_field :name %>
  <% personform.fieldsfor :children do |child_form| %>
    <%= childform.label :name %>
    <%= child
form.text_field :name %>
    <% unless childform.object.newrecord? %>
      <% # Don't forget to name both of these 'destroy' in Rails 3 %>
      <%= child
form.checkbox 'delete' %>
      <%= childform.label 'delete', 'Remove' %>
    <% end %>
  <% end %>
  <%= submit_tag %>
<% end %>

그리즈 몽키 ajax 콜


var jqxhr = $.ajax({
  type: "POST",
  url: trackback,
  headers: {'User-Agent': 'Trackback',
                  'Content-Type':'application/x-www-form-urlencoded; charset=utf8'},
  data: inputdata,
  datatype:"text"
   });
  jqxhr.done(function() {
    GM
log("Trackback Success : "+jqxhr.responseText);           
  });
  jqxhr.fail(function(data,statusText,error) {                
        GM_log("Trackback faild : "+statusText+" [ "+error+", "+data.responseText+" ]");              
       
       
  });
 

셀렉트 박스 정렬


sortingSelectBox(selectTagId,sortBy,order)
selectTagId <select id="selectTagId"></select>
sortBy [0:Text, 1:Value] - default:0
order[0:Ascending, 1:Descending] - default:0
Examples
sortingSelectBox("mySelectTagId",1,1) sortBy Value in Descending order
sortingSelectBox("mySelectTagId",1) sortBy Value in Ascending order
sortingSelectBox("mySelectTagId") sortBy Text in Ascending order
sortingSelectBox = (selectBoxId,sortBy,order) ->
   sortBy ?= 0
   order ?= 0
   sortVal = 0
   if order is 1 then sortVal = 2
   orderValLeft = -1 + sortVal
   orderValRight = 1 - sortVal
   selectBox = $("select#"+selectBoxId)
   options = $("select#"+selectBoxId+" option")
   selectedVal = selectBox.val()
   sortedOption = options.clone()
   options.empty().remove()
   switch sortBy
     when 0
       sortedOption.sort((left,right)->
         leftText = left.text.toLowerCase()
         rightText = right.text.toLowerCase()
         if leftText < rightText then return orderValLeft
         if leftText is rightText then return 0
         orderValRight
       )
     else
       sortedOption.sort((left,right)->
         leftVal = left.value
         rightVal = right.value
         if leftVal < rightVal then return orderValLeft
         if leftVal is rightVal then return 0
         orderValRight
       )
   selectBox.append(sortedOption)
   selectBox.val(selectedVal)
  
sortingSelectBox("country")

리다이렉트


// simulates similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// simulates similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

JQuery 데이터 타입


dataTypeString
Default: Intelligent Guess (xml, json, script, or html)
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:    "xml": Returns a XML document that can be processed via jQuery.
    "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
    "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
    "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
    "jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "
=[TIMESTAMP]", to the URL unless the cache option is set to true.
    "text": A plain text string.
    multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml." Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.
/*
If you wish to use any of the meta-characters
( such as !"#$%&'()*+,./:;?@[]^`{|}~ ) as a literal part of a name,
you must escape the character with two backslashes: . For example,
if you have an an element with id="foo.bar", you can use the selector
$("#foo.bar").
*/

Session based tokens


If you are using session based tokens, you probably generate a secure token when generating the session, and store that token in the session. When a request comes back to the server, you check that the token is included in the request and compare it to what's in the session. If it's the same token, you accept the request, if not you reject it.
To use this token with jQuery, you need to make it available to javascript. You typically do this by adding it as a javascript variable.
var csrftoken = '<%= tokenvalue %>';
Next, the trick is to bind to the global ajaxSend event, and add the token to any POST request
$("body").bind("ajaxSend", function(elm, xhr, s){
if (s.type == "POST") {
xhr.setRequestHeader('X-CSRF-Token', csrf_token);
}
});

rails-3-1-and-jquery-ui-assets 설정


# http://stackoverflow.com/questions/6133818/rails-3-1-and-jquery-ui-assets
 $ cat app/assets/javascripts/application.js
    //= require jquery
    //= require jquery-ui
    $ cat app/assets/stylesheets/application.css
    /*
     *= require vendor
     *
     */
    $ cat vendor/assets/stylesheets/vendor.css
    /*
     *= requiretree ./jqueryui
     *
     */
    vendor/assets/ $ tree
     stylesheets
         vendor.css
             jqueryui
                      jquery-ui-1.8.13.custom.css
                      ...
     images
        jquery
ui
            ui-bgflat0aaaaaa40x100.png
            ...

Finally run this command:
    vendor/assets/images $ ln -s jquery_ui/ images
   

Get center


$(document).ready(function(){
  jQuery.fn.center = function () {
      this.css("top",$(window).height()/2-this.height()/2 + "px");
      this.css("left",$(window).width()/2-this.width()/2  + "px");
      return this;
  }
  $("#container").center();
 });
 

Multiple selector

$("#txt1, #txt2, #txt3").keyup(fn);

Jquery check CKEditor


$(this).data('initialForm', $(this).serialize());
to
$(this).data('initialForm', $(this).serialize() + '&' + FieldNameOfEditor + '=' + escape(ContentsOfEditor));
And a similar change to line 4 from
if ($(this).data('initialForm') != $(this).serialize()) {
to
var formData = $(this).serialize() + '&' + FieldNameOfEditor + '=' + escape(ContentsOfEditor);
if ($(this).data('initialForm') != formData) {

Jquery Defer


(function() {
      function getScript(url,success){
        var script=document.createElement('script');
        script.src=url;
        var head=document.getElementsByTagName('head')[0],
            done=false;
        script.onload=script.onreadystatechange = function(){
          if ( !done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') ) {
            done=true;
            success();
            script.onload = script.onreadystatechange = null;
            head.removeChild(script);
          }
        };
        head.appendChild(script);
      }
        getScript('http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js',function(){
            // YOUR CODE GOES HERE AND IS EXECUTED AFTER JQUERY LOADS
        });
    })();

Scroll to top   


var destination = $(‘#idToScrollTo’).offset().top;
$(‘html’).animate({scrollTop: destination},600);

CKEDITOR


config.toolbar = 'Modati'
config.toolbar_Modati = [['Bold', 'Italic', 'Underline','Strike', '-', 'RemoveFormat','-', 'Outdent','Indent','-','Blockquote','HorizontalRule', '-', 'JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','FontSize','TextColor','BGColor']]CKEDITOR.editorConfig = function( config )
{
    config.toolbar = 'MyToolbar';
 
    config.toolbar_MyToolbar =
    [
        { name: 'document', items : [ 'NewPage','Preview' ] },
        { name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] },
        { name: 'editing', items : [ 'Find','Replace','-','SelectAll','-','Scayt' ] },
        { name: 'insert', items : [ 'Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'
                 ,'Iframe' ] },
                '/',
        { name: 'styles', items : [ 'Styles','Format' ] },
        { name: 'basicstyles', items : [ 'Bold','Italic','Strike','-','RemoveFormat' ] },
        { name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote' ] },
        { name: 'links', items : [ 'Link','Unlink','Anchor' ] },
        { name: 'tools', items : [ 'Maximize','-','About' ] }
    ];
};
config.toolbar = 'Full';
 
config.toolbarFull =
[
    { name: 'document', items : [ 'Source','-','Save','NewPage','DocProps','Preview','Print','-','Templates' ] },
    { name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] },
    { name: 'editing', items : [ 'Find','Replace','-','SelectAll','-','SpellChecker', 'Scayt' ] },
    { name: 'forms', items : [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton',
 
         'HiddenField' ] },
    '/',
    { name: 'basicstyles', items : [ 'Bold','Italic','Underline','Strike','Subscript','Superscript','-','RemoveFormat' ] },
    { name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote','CreateDiv','-
 
        ','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','BidiLtr','BidiRtl' ] },
    { name: 'links', items : [ 'Link','Unlink','Anchor' ] },
    { name: 'insert', items : [ 'Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak','Iframe' ] },
    '/',
    { name: 'styles', items : [ 'Styles','Format','Font','FontSize' ] },
    { name: 'colors', items : [ 'TextColor','BGColor' ] },
    { name: 'tools', items : [ 'Maximize', 'ShowBlocks','-','About' ] }
];
 
config.toolbar
Basic =
[
    ['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink','-','About']
];
CKEDITOR.editorConfig = function( config )
{
    config.extraPlugins = "customparagraph";
    config.toolbar = [ [ 'ThinyP' ] ]; // add other toolbars and keep in mid this can be overwritten in page which loads CKEditor
};
<script type="text/javascript">
//<![CDATA[
    // Replace the <textarea id="editor1"> with a CKEditor
    // instance, using default configuration.
    CKEDITOR.replace( 'editor1',
        {
            extraPlugins : 'customparagraph',
            toolbar :
            [
                [ 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink' ],
                [ 'ThinyP' ]
            ]
        });
//]]>
</script>
in the main ckeditor config-file there is an option to disable automatic <p> inserts. try to change the value of CKConfig.EnterMode and CKConfig.ShiftEnterMode for example to 'br'.
config.enterMode = CKEDITOR.ENTER_BR
lostmorethanfive, lostbeetweenfourandfive, lostbeetweenthreeandfour, lostbeetweentwoandthree, lostbeetweenoneandtwo, lostbeetweenzeroandone, gainedbeetweenzeroandone, gainedbeetweenoneandtwo,gainedbeetweentwoandthree, gainedbeetweenthreeandfour, gainedbeetweenfourandfive,gainedbeetweenfiveandsix, gainedbeetweensixandseven,gainedmorethanseven


출처




by


Tags : , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

자연의 경고 메시지를 전하는 존 윈담의 단편 소설. 거미줄.

트리피드의 날(The Day of the Triffids)을 쓴 영국의 SF 작가 존 윈담.
그가 죽은 지 십 년 후에 출간된 단편 소설입니다.
그의 다른 글은 읽어본 적이 없지만,
짤막한 이 소설은 그가 내공이 쌓인 작가라는 걸 여실히 보여 주는군요.

Web

“ 태초부터 인간의 삶의 일부였던 악과 어리석음, 그로부터 해방된 공동체!”
“이 신선한 공동체는 지성과 이성을 기반으로 운영될 것입니다!”

주인공은 그 공동체의 초기 회원으로써, 공동체의 기반을 새우러 모험을 떠납니다.
그리고 그곳에서 자연의 경고 메시지를 전해 듣게 돼요.
소설답게 재미난 건 물론이고, 사유거리를 던져줍니다.
언제부터 자연이 인간의 전유물이었나?
우리 또한 그의 일부인데, 환경을 파괴 하는 것은 스스로 파멸의 길로 걸어 가는 게 아닌가?
다른 이를 핍박해 빼앗은 것을, 남에게 팔아 배를 채우는 게 인간으로서 할 짓인가?



by


Tags : , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

특정 조건으로 검색을 자주 한다면, 자신만의 파이어폭스 검색 에드온을 만들어 보세요.

자주 쓰는 검색 조건이 있으신가요?

만약 특별히 자주 쓰는 검색 조건이 있다면,

기본 검색 에드온으로 검색한 다음에, 일일히 조건을 지정하시기는 참 귀찮은 일입니다.

자신만의 파이어폭스 검색 애드온을 만들면, 이런 수고를 덜어줘요.

 

파이어폭스용 검색 에드온 만들기

아래의 양식으로 문서를 만든 후 search-engine-name.xml 포멧으로 저장하세요.

firefox/Data/profile/searchplugins 폴더 혹은 Firefox/searchplugins 폴더에 파일을 복사해 넣으세요.

 

파이어폭스용 검색 에드온 양식

 

<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/" xmlns:os="http://a9.com/-/spec/opensearch/1.1/"><<os:ShortName>검색 엔진 이름</os:ShortName>
<os:Description>검색엔진 설명</os:Description>
<os:InputEncoding>UTF-8</os:InputEncoding>
<os:Image width="16" height="16">이미지의 base64코드</SearchForm>
<os:Url type="text/html" method="GET" template="검색엔진주소[query={searchTerms}]">
</os:Url>
</SearchPlugin>

 

아마 사람마다 즐겨 검색 하는 조건이 다를 거에요.

예를 들자면 저는 구글에서 최근 1년사이의 정보를 찾는 횟수가 잦습니다.

그리고 페이지 넘기는게 귀찮으니 한번에 50개 정도 검색 결과가 나오면 좋겠군요.

그리고 검색된 링크를 새 창으로 띄우면 더 편하겠어요.

이 조건을 적용하면 아래와 같은 검색 주소가 나옵니다.

 


http://www.google.com/search?num=50&amp;hl=en&amp;newwindow=1&amp;tbo=1&amp;output=search&amp;source=lnt&amp;tbs=qdr:y&amp;sa=X&amp;sourceid=navclient&amp;gfns=1&amp;q={searchTerms}

이 주소를 Url template 란에 넣어주면 되는거에요.

Image의 경우는 16*16 크기의 그림파일을 열어 base64코드로 변환해 줍니다.

아래 사이트에서 base64코드로 변경 할 수 있어요.

base64 sample decoder and encoder

 

이미지는 건너 뛰어도 무리없이 작동합니다.:D

 

또 제가 꽤 자주 쓰는 검색엔진이 있는데, 바로 국립국어원 표준국어대사전입니다.

국어 사전을 볼 때마다 제가 한국에 태어난 걸 참 다행이라고 생각해요.

이걸 외국어로 배우려고 했으면 얼마나 머리가 아팠을지.. 어휴.

 

파이어폭스용 국립국어원 표준국어대사전 검색 애드온이 필요하시다면 아래 링크에서 내려받으세요.

https://addons.mozilla.org/en-US/firefox/addon/표준국어대사전

 

검색 에드온에 대해 더 자세히 알고 싶다면 아래 링크를 참조하세요.

Creating OpenSearch plugins for Firefox

 



by


Tags : , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

원하는 DIV 레이어를 간편하게 프린트 해주는 Div Print Jquery 스크립트 입니다.

이 스크립트는 두 개의 메소드를 포함하고 있습니다.
printdiv 메소드와 printdiviframe 메소드인데요.
두 출력 메소드 모두 Jquery 라이브러리가 필요하고,
print
diviframe 메소드는 JqueryUI 모듈도 필요로 합니다.
print
div는 새 창을 띄워서 바로 프린트 하고,
printdiviframe는 JqueryUI의 다이얼로그를 이용해 출력 미리보기를 제공합니다.

print_div_iframe-'Print Div Jquery Coffeescript, Javascript'

div 출력하는 커피스크립트나 자바스크립트가 필요하신 분은 가져다 쓰세요~

Div Print Jquery 스크립트 소스 다운로드



by


Tags : , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

모질라 파이어폭스에서 Ajax 한글 키 이벤트를 처리하는 Jquery,커피스크립트 코드입니다.

모질라 파이어폭스 Ajax. 한글 키 이벤트 처리.(Jquery Mozilla Force Keyup CoffeeScript module)

저는 주 브라우저로 모질라 파이어폭스를 사용합니다.
Ajax 모듈을 만드는데, 한글을 입력하면 못 알아듣더군요.
http://javascript.info/tutorial/keyboard-events에서 키 이벤트 체크를 해 봤습니다.
한글 키가 눌리면 Keydown(Keycode=229) 이벤트가 한 번만 발생하고,
Keyup 이벤트는 발생하지 않습니다.
중국어,일본어를 테스트 해보니 이 역시 같은 현상이군요.
한글과 다름없이 229키 코드가 딱 한번 발생합니다.
아마도 다른 블록형 문자 또한 같은 이벤트를 발생 시킬 거라 예상됩니다.
모질라에서 한글 키 이벤트를 부드럽게 처리하는 커피 스크립트 모듈을 만들었어요.
모질라 파이어폭스 이용자도 한글을 편하게 쓸 권리가 있으니까요.
필요하신 분은 마음껏 가져다 쓰세요.

커피스크립트 버전(Jquery Mozilla Force Keyup module  - Coffeescript version)



  
# Mozilla Force Keyup CoffeeScript module
# by 月風(http:://dorajistyle.pe.kr)
# How to use
# mozillaForceKeyup(”inputid”)
# in HTML.
# <input id=”input
id”>
mozillaForceKeyup = (targetId) ->
  if jQuery.browser.mozilla
    isIntervalRunning = null
    target = '#'+targetId
    $(target).bind 'keydown',(e) ->
      if e.which == 229
        forceKeyup = () ->
          $(target).trigger('keyup')
        if not isIntervalRunning
          isIntervalRunning = setInterval forceKeyup, 100

    $(target).bind 'blur',(e) ->
      if isIntervalRunning
        clearInterval isIntervalRunning
        isIntervalRunning = null



자바스크립트 버전(Jquery Mozilla Force Keyup module - Javascript version)



// Mozilla Force Keyup Javascript module
// by 月風(http:://dorajistyle.pe.kr)
// How to use
// mozillaForceKeyup(”inputid”)
// in HTML.
// <input id=”input
id”>

mozillaForceKeyup = function(targetId) {
var isIntervalRunning, target;
if (jQuery.browser.mozilla) {
isIntervalRunning = null;
target = '#' + targetId;
$(target).bind('keydown', function(e) {
var forceKeyup;
if (e.which === 229) {
forceKeyup = function() {
return $(target).trigger('keyup');
};
if (!isIntervalRunning) {
return isIntervalRunning = setInterval(forceKeyup, 100);
}
}
});
return $(target).bind('blur', function(e) {
if (isIntervalRunning) {
clearInterval(isIntervalRunning);
return isIntervalRunning = null;
}
});
}
};







by


Tags : , , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

It’s a simple code for ‘Sorting a select box’ using jquery, coffeescript

Sorting a Select box using Jquery, Coffeescript


I tried to find coffeescript code for sorting a select box.
But I didn’t find it.

Cause I just wrote own sorting select box code using jquery and coffeescript.

Copy and Paste below sorting select box coffeescript code and use it Freely.:D

Jquery, Coffeescript를 이용한 Select box 정렬 함수 입니다.

Simple Select Sorting Code (CoffeeScript Version)



 


#--Simple Select Sorting Method. (S3M:D)--

#sortingSelectBox(selectTagId,sortBy,order)

#selectTagId <select id="selectTagId"></select>

#sortBy [0:Text, 1:Value] - default:0

#order[0:Ascending, 1:Descending] - default:0

#Examples

#sortingSelectBox("mySelectTagId",1,1) sortBy Value in Descending order

#sortingSelectBox("mySelectTagId",1) sortBy Value in Ascending order

#sortingSelectBox("mySelectTagId") sortBy Text in Ascending order

#

#by JoongSeob Vito Kim - http://dorajistyle.pe.kr

sortingSelectBox = (selectBoxId,sortBy,order) ->

  sortBy ?= 0

  order ?= 0

  sortVal = 0

  if order is 1 then sortVal = 2

  orderValLeft = -1 + sortVal

  orderValRight = 1 - sortVal

  selectBox = $("select#"+selectBoxId)

  options = $("select#"+selectBoxId+" option")

  selectedVal = selectBox.val()

  sortedOption = options.clone()

  options.empty().remove()

  switch sortBy

    when 0

      sortedOption.sort((left,right)->

        leftText = left.text.toLowerCase()

        rightText = right.text.toLowerCase()

        if leftText < rightText then return orderValLeft

        if leftText is rightText then return 0

        orderValRight

      )

    else

      sortedOption.sort((left,right)->

        leftVal = left.value

        rightVal = right.value

        if leftVal < rightVal then return orderValLeft

        if leftVal is rightVal then return 0

        orderValRight

      )

  selectBox.append(sortedOption)

  selectBox.val(selectedVal)

 



  

Simple Select Sorting Code (JavaScript Version)


 


//Simple Select Sorting Method. (S3M:D)

//sortingSelectBox(selectTagId,sortBy,order)

//selectTagId <select id="selectTagId"></select>

//sortBy [0:Text, 1:Value] - default:0

//order[0:Ascending, 1:Descending] - default:0

//Examples

//sortingSelectBox("mySelectTagId",1,1) sortBy Value in Descending order

//sortingSelectBox("mySelectTagId",1) sortBy Value in Ascending order

//sortingSelectBox("mySelectTagId") sortBy Text in Ascending order

//

//by JoongSeob Vito Kim - http://dorajistyle.pe.kr

sortingSelectBox = function(selectBoxId, sortBy, order) {

var options, orderValLeft, orderValRight, selectBox, selectedVal, sortVal, sortedOption;

if (sortBy != null) {

sortBy;

} else {

sortBy = 0;

};

if (order != null) {

order;

} else {

order = 0;

};

sortVal = 0;

if (order === 1) {

sortVal = 2;

}

orderValLeft = -1 + sortVal;

orderValRight = 1 - sortVal;

selectBox = $("select#" + selectBoxId);

options = $("select#" + selectBoxId + " option");

selectedVal = selectBox.val();

sortedOption = options.clone();

options.empty().remove();

switch (sortBy) {

case 0:

sortedOption.sort(function(left, right) {

var leftText, rightText;

leftText = left.text.toLowerCase();

rightText = right.text.toLowerCase();

if (leftText < rightText) {

return orderValLeft;

}

if (leftText === rightText) {

return 0;

}

return orderValRight;

});

break;

default:

sortedOption.sort(function(left, right) {

var leftVal, rightVal;

leftVal = left.value;

rightVal = right.value;

if (leftVal < rightVal) {

return orderValLeft;

}

if (leftVal === rightVal) {

return 0;

}

return orderValRight;

});

}

selectBox.append(sortedOption);

return selectBox.val(selectedVal);

};



 

  
by 月風



by


Tags : , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

Perl에서 Jquery를 이용해 email 중복을 검사하는 방법입니다.

Perl에서 Jquery를 이용해 email 중복 검사 하기

-'Perl에서  Jquery를 이용한 email 중복체크 하기'

저는 이번에 Perl을 처음 건드려 봅니다.
'펄 세계엔, 한줄의 코드로 컴퓨터를 주므르는 고수들이 살고 있다!'
한참 전에 이런 소리를 들어 봤던거 같군요.
그때 든 생각은.
'한줄? 아! 디버깅하기 힘들겠구나.' 였어요.
인간 친화적이라기보다 기계 친화적인 언어라고 생각했었죠.
펄로 만들어진 PHP는 친숙하지만 Perl이라면 왠지 거리감이 느껴지는 언어였어요.
그런데 Perl에서도 요즘 흔히 쓰는 Jquery를 이용한 Ajax 구현이 가능합니다.
덕분에 조금 가까워 졌네요.:D


duplicate_test.html
<html><head/><body>
<INPUT maxLength=12 name="email" id="email" size="20"><br/>

<div id="duplicateResult"></div>
<script type="text/javascript" src="/rfo/jquery.js"></script>

<script type="text/javascript" src="/rfo/duplicate.js"></script>
</body></html>


duplicate.js
$(document).ready(function(){
  $("#email").keyup(function() {
    var email = $('#email').attr('value'); // get email
        if (email) { // values are not empty   
      $.ajax({
        type: "GET",
        url: "/cgi-bin/duplicate.pl", // URL of the Perl script
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "email=" + email,       
        // script call was not successful
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          $('div#duplicateResult').text("responseText: " + XMLHttpRequest.responseText
            + ", textStatus: " + textStatus
            + ", errorThrown: " + errorThrown);
          $('div#duplicateResult').addClass("error");
        }, // error
        // script call was successful
        // data contains the JSON values returned by the Perl script
        success: function(data){
          if (data.vacancy) { // script returned error
            $('div#duplicateResult').html("<span style='color:blue;font-size:14px;font-weight:bold;'>" + data.vacancy+"</span>");
            $('div#duplicateResult').addClass("vacancy");
          } // if
          else { // login was successful
            $('div#duplicateResult').html("<span style='color:red;font-size:14px;font-weight:bold;'>" + data.occupied+"</span>");
            $('div#duplicateResult').addClass("occupied");
          } //else
        } // success
      }); // ajax
    } // if
    else {
      $('div#duplicateResult').text("아이디를 입력해 주세요.");
      $('div#duplicateResult').addClass("error");
    } // else
    $('div#duplicateResult').fadeIn();
    return false;
  });
});


duplicate.pl

!/usr/bin/perl

use CGI;
use DBI;
use strict;
use warnings;
use rfoconfig;


read the CGI params

my $cgi = CGI->new;
my $email = $cgi->param("email");


connect to the database

my $dbh = DBI->connect("DBI:mysql:testDB:localhost","user","password");


check the username and password in the database

my $statement = qq{SELECT COUNT(*) FROM user WHERE email=?};
my $sth = $dbh->prepare($statement)  or die $dbh->errstr;
$sth->execute($email)  or die $sth->errstr;
my ($duplicatekey) = $sth->fetchrowarray;

my $json = ($duplicate_key) ?
  qq{{"occupied" : " $email는 이미 있는 아이디 입니다."}} :
  qq{{"vacancy" : "$email을 사용하실 수 있습니다."}};


return JSON string


"DBI:mysql:testDB:localhost","user","password"
우선 위 코드에서 testDB:localhost , user, password는 테스트 환경에 맞게 설정해 주세요.

print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json;
아래 파일은 Document root/ 에 넣으세요.

  • Jquery.js (http://jquery.com 에서 다운로드 받으세요.)
  • duplicate.js
  • duplicate_test.html

아래 파일은 Document root/cgi-bin 에 넣으세요.

  • duplicate.pl


 

참고자료
Very simple login using Perl, jQuery, Ajax, JSON and MySQL

by 月風



by


Tags : , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

모질라 파이어폭스 포터블을 상위 버젼으로 업데이트 할 때, 쓰던 환경 설정을 그대로 사용 하는 간단한 방법을 소개합니다.

오랫동안 파이어폭스 3.6.18버젼을 써 오다가 이번에 파이어폭스를 두 차례나 업데이트 했습니다.
파이어폭스 5.0.1버젼으로 버젼을 올렸을땐 왠지 모르게 엄청 버벅이더군요.
오랫동안 친하게 지내왔던 모질라 파이어폭스를 외면해 버리고 싶을 정도로...
그래서 6.0b를 다운받아 사용해 보니 아주 만족스럽네요.
설정에 대한 이야기를 하기 전에 우선,버젼별 메모리 점유율과, 모양을 비교해 보겠습니다.
by 月風


파이어폭스 포터블 설정

3.6.18 메모리 점유율-'파이어폭스 포터블 설정'
파이어폭스 3.6.18에서의 메모리 점유율
5.0.1 메모리 점유율-'파이어폭스 포터블 설정'
파이어폭스 5.0.1에서의 메모리 점유율
6.0b 메모리 점유율-'파이어폭스 포터블 설정'
파이어폭스 6.0b에서의 메모리 점유율

아무래도. 6.0b를 쓸 때 부가기능을 하나 지우고,
부가기능 하나는 옵션을 조정한 것이 크게 도움이 된 것 같습니다.
지워버린 파이어폭스 부가기능은 SeoQuake에요. 사이트의 페이지랭크와 인바운드 링크등을 보여주는 SEO도우미죠.
그런데 제가 쓰기엔 너무 무거운 부가기능 입니다. 그래서 과감히 지웠죠. 체감속도가 바로 올라가는군요.
그리고 설정을 변경한 부가기능은 Yslow에요. 페이지 로딩 속도를 빠르게 하기 위한 체크리스트를 보여주는 툴로 아주 유용합니다.
하지만 사용할 때만 켜서 써도 충분해요. 페이지를 로딩할 때 마다 몇 초 걸리는지 계산을 할 필요는 없죠.
이렇게 부가기능을 정리하고 나니 확실히 체감 속도가 올라갔습니다.

3.6.18 화면-'파이어폭스 포터블 설정'
모질라 파이어폭스 3.6.18 화면

5.0.1 화면-'파이어폭스 포터블 설정'
모질라 파이어폭스 5.0.1 화면

6.0b 화면-'파이어폭스 포터블 설정'
모질라 파이어폭스 6.0b 화면

파이어폭스 3.6.18에서 5.01로 바꾸었을땐 '꼭 크롬 같이 바뀌었네.' 라는 생각이 들었고,
5.01버젼과 6.0b버전은 보기에 별 차이가 없네요.
그럼 이제 본론으로 들어가겠습니다.
버전을 올릴 때 마다 설정을 다시 해 줘야 한다면 여간 귀찮은 일이 아니죠?
원래 있던 파이어폭스의 폴더 하나만 새 버젼의 파이어폭스 폴더에 복사하면 쓰던 설정 그대로 사용 할 수 있습니다.
 

FirefoxPortable\Data\profile
 

이 설정 폴더를 새로운 버전의 파이어폭스에 복사하시면 됩니다.
이제 설정은 쓰던 그대로 인데, 버전이 올라가면서 부가기능을 사용할 수 없게 되는 경우가 있어요.
그럴 땐 호환성을 관리해주는 Add-on Compatibility Reporter 부가기능을 설치하시면,
낮은 버전에서 쓰던 부가기능을 사용할 수 있어요.:D

파이어폭스 포터블 테스트 버젼 다운로드 (6.0b)

파이어폭스 포터블 다운로드(5.01)



by


Tags : , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

 

구글,키워드,검색,google,keyword,search,test,검색,실험


포스트
태그로 검색하여 연관글을 보여주는 Google AJAX Search 적용을 위해, 최상의 검색옵션이 필요 했습니다.

저에게 필요한 검색 옵션은 이것입니다.

태그 ∩ 포스트 > 0

포스트에 적어도 한개의 태그가 포함되어야 하는것이죠.

태그를 키워드로 하여 아래의 방법으로 실험을 했습니다.

Open english content




1. 공백으로 키워드 구분 (Space delimited Keyword) [검색결과(Search result) = 0]

 family hollywood LA Los Angeles manhatan beach north america travel United States universal studio 가족 로스엔젤레스 맨하튼비치 미국 북미 여행 유니버설스튜디오 헐리우드site:dorajistyle.pe.kr

    아무것도 나오지 않습니다. (Result not found)


2. OR로 키워드 구분 (OR delimited Keyword) [검색결과(Search result) ≒ 3]

family OR hollywood OR LA OR Los Angeles OR manhatan beach OR north america OR travel OR United States OR universal studio OR 가족 OR 로스엔젤레스 OR 맨하튼비치 OR 미국 OR 북미 OR 여행 OR 유니버설스튜디오 OR 헐리우드 site:dorajistyle.pe.kr

    고급 검색에서 '다음 단어 적어도 하나 포함'을 이용하여 검색을 하면 같은 결과가 나옵니다.


3. 작은 따옴표와 쉼표로 키워드 구분 (Single quotation marks and comma
delimited Keyword) [검색결과(Search result)  = 0]

'family','hollywood','LA','Los Angeles','manhatan beach','north america','travel','United States','universal studio','가족','로스엔젤레스','맨하튼비치','미국','북미','여행','유니버설스튜디오','헐리우드' site:dorajistyle.pe.kr

    아무것도 나오지 않습니다. (Result not found)


4. 큰 따옴표와 쉼표로 키워드 구분 (Double quotation marks and comma delimited Keyword) [검색결과(Search result) ≒ 1]

"family","hollywood","LA","Los Angeles","manhatan beach","north america","travel","United States","universal studio","가족","로스엔젤레스","맨하튼비치","미국","북미","여행","유니버설스튜디오","헐리우드" site:dorajistyle.pe.kr

    태그가 모두 포함되어있는 글이 검색되었습니다. (One result that have )


5. 작은 따옴표와 OR로 키워드 구분 (Single quotation mark and OR delimited Keyword) [검색결과(Search result) ≒ 3]

'family' OR 'hollywood' OR 'LA' OR 'Los Angeles' OR 'manhatan beach' OR 'north america' OR 'travel' OR 'United States' OR 'universal studio' OR '가족' OR '로스엔젤레스' OR '맨하튼비치' OR '미국' OR '북미' OR '여행' OR '유니버설스튜디오' OR '헐리우드' site:dorajistyle.pe.kr

    고급 검색에서 '다음 단어 적어도 하나 포함'을 이용하여 검색을 하면 같은 결과가 나옵니다.


6. 큰 따옴표와 OR로 키워드 구분 (Double quotation mark and OR delimited Keyword) [검색결과(Search result) ≒ 30+]

"family" OR "hollywood" OR "LA" OR "Los Angeles" OR "manhatan beach" OR "north america" OR "travel" OR "United States" OR "universal studio" OR "가족" OR "로스엔젤레스" OR "맨하튼비치" OR "미국" OR "북미" OR "여행" OR "유니버설스튜디오" OR "헐리우드" site:dorajistyle.pe.kr

    드디어 원하는 결과를 얻었습니다. 사실 한국어 구글이 아닌 영문 구글 사이트에서는 '다음 단어 적어도 하나 포함' 사이에 친절하게 OR 이 들어있고, 자동으로 큰 따옴표를 추가해 줍니다.
   (You can get same result at Advanced Search's one or more of these words option)




결론은 큰 따옴표로 "키워드" 를 묶어서 검색을 하는 것이 답입니다.

(Wrap "Keywords" with double quotation is best way to search.)




by


Tags : , , , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

구글 크롬에서 그리즈몽키 사용하기 (How to use greasemonkey in chrome)[크롬,그리즈몽키,chrome,greasemonkey]

이미지출처 : www.guru63.com

구글 크롬에서 그리즈몽키 사용하기 (How to use greasemonkey in chrome)











현재 좌파폭 우크롬을 쓰고 있다.

파폭은 주로 API볼때랑 검색할때 사용하고,

크롬은 업무보고, trac,  블로그, 미투데이등 뭔가 작성할때 사용하고 있다.

그리하여.. 블로그에 글을 올릴때도 크롬을 사용하는데,

피카사에서 사진 링크를 가져올때마다 너무 불편한거다.ㅠㅠ

피카사 페이지를 좀 편하게 만들고 싶어서 찾아봤더니 괜찮은 그리즈몽키 스크립트가 있는데,

크롬에서 쓸라고 하니 플러그인을 설치할수도 없고..

아 어찌하나, 파폭에서 써야되나..

그리즈몽키를 크롬에서는 사용할 수 없을까?

이런저런 생각을 하면서 구글한테 물어보니 이것저것 많이 나와서 찾아보다보니,

좀 부실하긴 하지만 나름 간단하게 쓸 수 있게 되어있었다.

----

I use browsers likes that firefox on left,chrome on right.

Firefox use to see API and search anything.

Chrome use to write a report and create posts on blog.

When I posting, I am felling like an inconvenience cause It's uncomfortable that I get image link on Google Picasa.

Then I decide to use greasemonkey for getting image link more comfortable.

But chrome not support plug-ins yet, what can I do?


1. 크롬을 설치한다.
   Install a recent Chrome.

2. 크롬을 실행할때 --enable-greasemonkey 옵션을 준다.
   Launch chrome with the --enable-greasemonkey flag.
   (숏컷에서 사용할경우 "PATH/chrome.exe" "--enable-greasemonkey")

3. C:/scripts 폴더에 그리즈 몽키파일(*.user.js)을 넣는다.
   Copy greasemonkey file(*.user.js) to the C:/scripts.

4. 해당페이지로 가서 새로고침을 해보고, 적용이되면 그대로 사용하고, 아니면 크롬을 재시동 한다.
   Just refresh the page or relaunch chrome.
 
 
끝~~!
The end.



아 이 얼마나 간편한가?!
How simple it?!

필요한 그리즈몽키 코드들은 Userscripts.org에서 쉽게 구할수 있다.
You can get easily any greasemonkey scripts in Userscripts.org.

편하게 살자.ㅋ
Live comfortable!:D


[Reference]
http://mashable.com/2008/12/15/google-chrome-greasemonkey-scripts/



by


Tags : , , , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!