Created
March 5, 2011 06:08
-
-
Save yunjian/856169 to your computer and use it in GitHub Desktop.
Integrating avatar in Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#- add gem avatar in Gemfile | |
gem 'avatar', :git => '[email protected]:yunjian/avatar.git' | |
#- add sized gravatar source in | |
# {RAILS_ROOT}/lib/sized_gravatar_source.rb | |
require 'avatar/source/gravatar_source' | |
class SizedGravatarSource < Avatar::Source::GravatarSource | |
alias_method :parse_options_without_size, :parse_options | |
def self.sizes | |
{ :small => 50, :medium => 100, :large => 150, :big => 150 } | |
end | |
def parse_options(profile, options) | |
#pass :gravatar_size through, but translate :size or :s to a number if possible | |
parsed_options = parse_options_without_size(profile, options) | |
[:size, :s].each do |k| | |
parsed_options[k] = self.class.sizes[options[k]] if self.class.sizes.has_key?(options[k]) | |
end | |
parsed_options | |
end | |
end | |
#- add config/initializers/avatar_sources.rb | |
require 'avatar' | |
require 'avatar/source/paperclip_source' | |
require 'avatar/source/source_chain' | |
require 'avatar/source/static_url_source' | |
require 'avatar/source/wrapper/rails_asset_source_wrapper' | |
require 'avatar/source/wrapper/string_substitution_source_wrapper' | |
require 'sized_gravatar_source' | |
default = Avatar::Source::Wrapper::RailsAssetSourceWrapper.new( | |
Avatar::Source::Wrapper::StringSubstitutionSourceWrapper.new( | |
Avatar::Source::StaticUrlSource.new('/images/avatar_default_#{size}.png'), | |
{:size => :small} | |
) | |
) | |
chain = Avatar::Source::SourceChain.new | |
chain << Avatar::Source::PaperclipSource.new(:icon) | |
chain << Avatar::Source::TwitterSource.new(:twitter_name) | |
chain << SizedGravatarSource.new(default, :email) | |
Avatar::source = chain | |
#- add helper function | |
require 'avatar/view/action_view_support' | |
include Avatar::View::ActionViewSupport | |
def icon profile, size = :small, img_opts = {} | |
return "" if profile.nil? | |
img_opts = {:title => profile.name, :alt => profile.name, :class => size}.merge(img_opts) | |
link_to(avatar_tag(profile, {:size => size, :paperclip_style => size}, img_opts), profile_path(profile)) rescue '' | |
end | |
#- in view | |
<div class="avatar"><%= icon @lesson, :big %></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment