almost 4 years ago

系統:

Mac OS X Yosemite 10.10.1
Ruby 2.2.0
Rails 4.2.0

相關連結

Google QR Code API ( https://google-developers.appspot.com/chart/infographics/docs/qr_codes )

設定步驟如下

1. Helper 設定

新增 app/helpers/hash_helper.rb

module HashHelper
  ############
  ### Hash ###
  ############

  # Returns a specific value from the given hash (or the default value if not set).
  def get_value(key, hash, default_value = nil)
    value = hash.delete(key)
    value = default_value if value.nil? and !default_value.nil?
    value
  end

  # Removes and returns a specific value from the given hash (or the default value if not set).
  def pop_value(key, hash, default_value = nil)
    symbolize_keys(hash)
    get_value(key.to_sym, hash, default_value)
  end

  # all keys of the given hash symbolize.
  def symbolize_keys(hash)
    hash.replace(hash.symbolize_keys)
  end
end

新增 app/helpers/utility_helper.rb

module UtilityHelper
  def qrcode(data='', **options)
    # Google API: https://google-developers.appspot.com/chart/infographics/docs/qr_codes
    width = pop_value(:width, options, '200')
    output_encoding = pop_value(:output_encoding, options)
    error_correction_level = pop_value(:error_correction_level, options)
    margin = pop_value(:margin, options)

    qrcode_url = 'https://chart.googleapis.com/chart?cht=qr'
    qrcode_url += "&chl=#{data}"
    qrcode_url += "&chs=#{width}x#{width}"
    qrcode_url += "&choe=#{output_encoding}" unless output_encoding.nil?
    if error_correction_level.nil? or margin.nil?
      qrcode_url += %(&chld=#{error_correction_level}) unless error_correction_level.nil?
      qrcode_url += %(&chld=|#{margin}) unless margin.nil?
    else
      qrcode_url += %(&chld=#{error_correction_level}|#{margin})
    end
    image_tag(qrcode_url, alt: data)
  end
end

Options 參數可參見 此說明

2. View 設定

使用方式如下

<%= qrcode('http://chouandy.logdown.com/') %>

http://chouandy.logdown.com/

← Post 管理 - part 6 - Ajax Search Ruby on Rails 中使用支援 Syntax Highlighter 的 Markdown Template →
 
comments powered by Disqus