Ruby知识积累1

4 篇文章 0 订阅
  • 书写风格:
    •   Bad:
          if ! tweets.empty?
            puts "Timeline:"
            puts tweets
          end
        Good:
          unless tweets.empty?
            puts "Timeline:"
            puts tweets
          end
      
      
        Bad:
          unless tweets.emtpy?
            puts "Timeline:"
            puts tweets
          else
            puts "No tweets found - better follow some people."
          end
        Good:
          if tweets.empty?
            puts "Timeline:"
            puts tweets
          else
            puts "No tweets found - better follow some people."
          end
      
      
        Bad:
          if attachment.file_path != nil
            attachment.post
          end
        Good:
          if attachment.file_path
            attachment.post
          end
      
      
        Bad:
          if password.length < 8
            fail "Password too short"
          end
          unless username
            fail "No user name set."
          end
        Good:
          fail "Password too short" if password.length < 8
          fail "No user name set." unless username
      
      
        Bad:
          if user
            if user.signed_in?
              ...
            end
          end
        Good:
          if user && user.signed_in?
            ...
          end
      
      
        Bad:
          if list_name
            options[:path] = "/#{user_name}/#{list_name}"
          else
            options[:path] = "/#{user_name}"
          end
        Good:
          options[:path] = if list_name
            "/#{user_name}/#{list_name}"
          else
            "/#{user_name}"
          end
      
      
        Bad:
          def list_url(user_name, list_name)
            if list_name
              url = "https://twitter.com//#{user_name}/#{list_name}"
            else
              url = "https://twitter.com//#{user_name}"
            end
            url
          end
        Good:
          def list_url(user_name, list_name)
            if list_name
              "https://twitter.com//#{user_name}/#{list_name}"
            else
              "https://twitter.com//#{user_name}"
            end
          end
      
      
        Bad:(对于可选参数)
          def tweet(message, lat, long)
            #...
          end
          tweet("Practicing Ruby-Fu!", nil, nil)
        Good:
          def tweet(message, lat=nil, long=nil)
            #...
          end
          tweet("Practicing Ruby-Fu!")
      
      
        Bad:(Hash参数)
          def tweet(message, lat=nil, long=nil, reply_id=nil)
            #...
          end
          tweet("Practicing Ruby-Fu!", nil, nil, 227946)
        Good:
          def tweet(message, options={})
            status = Status.new
            status.lat = options[:lat]
            status.long = options[:long]
            status.body = message
            status.reply_id = options[:reply_id]
          end
          tweet("Practicing Ruby-Fu!", :lat => 28.55, :long => -81.33, :reply_id => 227946)
          Ruby>1.9
            tweet("Practicing Ruby-Fu!", lat: 28.55, long: -81.33, reply_id: 227946)
      
      
        Bad:(异常)
          def get_tweets(list)
            if list.authorized?(@user)
              list.tweets
            else
              []
            end
          end
      
      
          tweets = get_tweets(my_list)
          if tweets.empty?
            alert "No tweets were found!" + "Are you authorized to access this list?"
          end
        Good:
          def get_tweets(list)
            unless list.authorized?(@user)
              raise AuthorizationException.new
            end
            list.tweets
          end
      
      
          begin
            tweets = get_tweets(my_list)
          rescue AuthorizationException
            warn "You are not auhorized to access this list."
          end
      
      
        Bad:(类)
          user_names = [["Ashton", "Kutcher"],["Wil", "Wheaton"],["Madonna"]]
          user_names.each { |n| puts "#{n[1]},#{n[0]}" }
        Good:
          class Name
            def initialize(first, last = nil)
              @first = first
              @last = last
            end
            def format
              [@last, @first].compact.join(', ')
            end
          end
          user_names = []
          user_names << Name.new("Ashton", "Kutcher")
          user_names << Name.new("Wil", "Wheaton")
          user_names << Name.new("Madonna")
          user_names.each{ |n| puts n.format }
      
      
        Bad:(勿过度开放属性权限)
          class Tweet
            attr_accessor :status, :created_at
            def initialize(status)
              @status = status
              @created_at = Time.now
            end
          end
        Good:
          class Tweet
            attr_accessor :status
            attr_reader :created_at
            def initialize(status)
              @status = status
              @created_at = Time.now
            end
          end
      
      
        Bad:(累的继承)
          class Image
            attr_accessor :title, :size, :url
            def to_s
              "#{@title}, #{@size}"
            end
          end
          class Video
            attr_accessor :title, :size, :url
            def to_s
              "#{@title}, #{@size}"
            end
          end    
        Good:
          class Attachment
            attr_accessor :title, :size, :url
            def to_s
              "#{@title}, #{@size}"
            end
          end
          class Image < Attachment
          end
          class Video < Attachment
          end
      
      
        Bad:
          class User
            def tweet_header
              [@first_name, @last_name].join(' ')
            end
            def profile
              [@first_name, @last_name].join(' ') + @description
            end
          end
        Good:
          class User
            def display_name
              title = case @gender
              when :female  then married? ? "Mrs." : "Miss"
              when :male    then "Mr."
              end
              [title, @first_name, @last_name].join(' ')
            end
            def tweet_header
              display_name
            end
            def profile
              display_name + @description
            end
          end
  • 类:
    •   class UserList
          attr_accessor :name
          def initialize(name)
            self.name = name
          end
        end
        list = UserList.new('Andy')
        list.name----------->Andy
  • 平板型参数:
    •   def metion(status, *names)
          tweet("#{names.join(',')} #{status}")
        end
        metion('Your courses rocked!', 'eallam', 'greggpollack','jasonvanlue')
  • CASE语句:
    •  client_url = case client_name
        when "web"
          "http://twitter.com"
        else
          nil
        end
      
      
        popularity = case tweet.retweet_count
        when 0..9
          nil
        else
          "hot"
        end
      
      
        tweet_type = case tweet.status
        when /\A@\w+/
          :mention
        when /\Ad\s+\w+/
          :direct_message
        else
          :public
        end
      
      
        tweet_type = case tweet.status
        when /\A@\w+/     then  :mention
        when /\Ad\s+\w+/  then  :direct_message
        else                    :public
        end
  • Ruby中的FALSE:nil
  ""--------->true
  0 --------->true
  []--------->true
  • Ruby中赋值便捷方法:
    •   当result为nil时,赋值1
          result ||= 1
        若express1 || express2中,express1为False时,采用express2的值。
          result = nil || 1 ......> 1
          result = 1 || nil ......> 1
          result = 1 || 2   ......> 1
          def sign_in
            current_ssession || sign_uer_in
          end
  • ActiveSupport:
    •   gem install activesupport
        gem install i18n
      
        require 'active_support/all'
    •   对数组的扩展:
      •     array = [0,1,2,3,4,5,6]
            array.from(4)
            array.to(2)
            添加nil元素补齐:
              array.in_groups_of(3)---->[[0,1,2],[3,4,5],[6,nil,nil]]
            以分隔元素为轴划分,并将分隔元素删除:
              array.split(2)---->[[0,1],[3,4,5,6]]
    •   对Date的扩展:
      •     apocalypse = DateTime.new(2014,7,6,12,49,30)
            apocalypse.at_beginning_of_day
            apocalypse.at_end_of_month
            apocalypse.at_beginning_of_year
            apocalypse.advance(years: 4, months: 3, weeks: 2, days: 1)
            apocalypse.tomorrow
            apocalypse.yesterday
    •   对Hash的扩展:
      •     options = {user: 'codeschool', lang: 'fr'}
            new_options = {user: 'codeschool', lang: 'fr', password: 'dunno'}
            options.diff(new_options)
            将键值转换成字符串:
              options.stringify_keys
            合并Hash,以options为主:
              options.reverse_merge(new_options)
            new_options.except(:password)
            new_options.assert_valid_keys(:user, :lang)
    •   对Integer的扩展:
      •     def background_class(index)
              return 'white' if index.odd?
              return 'grey' if index.even?
            end
            tweets.each_with_index do |tweet, index|
              puts "<div class='#{background_class(index)}'>#{tweet}</div>"
            end
  •   inflector:
    •     1.ordinalize
          "user".pluralize
          "users".singularize
          "ruby".titleize
          "account_options".humanize
  • 命名空间:
    •   Bad:(污染了全局方法,可能会和同名方法冲突。)
          image_utils.rb
            def preview(image)
            end
            def transfer(image, destination)
            end
          run.rb
            require 'image_utils'
            image = user.image
            preview(image)
        Good:
          image_utils.rb
            module ImageUtils
              def self.preview(image)
              end
              def self.transfer(image, destination)
              end
            end
          run.rb
            require 'image_utils'
            image = user.image
            ImageUtils.preview(image)
  •   MIXIN:
    •       module ImageUtils
              def preview
              end
              def transfer(destination)
              end
            end
      
      
            require 'image_utils'
            class Image
              include ImageUtils
            end
      
      
            image = user.image
            image.preview(image)
  • HOOKS:(self.include)
    •   未用self.include:
          模块:
            module ImageUtils
              def preview
              end
              def transfer(destination)
              end
              module ClassMethods
                def fetch_from_twitter(user)
                end
              end
            end
          类:
            class Image
              include ImageUtils
              extend ImageUtils::ClassMethods
            end
          调用:
            image = user.image
            image.preview
            Image.fetch_from_twitter('grege')
        使用self.include:
          模块:
            module ImageUtils
              def self.included(base)
                base.extend(ClassMethods)
              end
              def preview
              end
              def transfer(destination)
              end
              module ClassMethods
                def fetch_from_twitter(user)
                end
              end
            end
          类:
            class Image
              include ImageUtils
            end
          调用:
            image = user.image
            image.preview
            Image.fetch_from_twitter('grege')
        使用activesupport gem:
          模块:
            require 'active_support/concern'
            module ImageUtils
              extend ActiveSupport::Concern
              included do
                clean_up
              end
      
      
              def preview
              end
              def transfer(destination)
              end
              module ClassMethods
                def fetch_from_twitter(user)
                end
      
      
                def clean_up
                end
              end
            end
          类:
            class Image
              include ImageUtils
            end
  • Blocks:
    •   e.g.
          words = ['Had','eggs','for']
          for index in 0..(words.length-1)
            puts words[index]
          end
      
      
          words.each { |word| puts word }
          or
          words.each do |word|
            puts word
          end
  • Yield:
    •   e.g.
          def call_this_block
            yield "tweet"
          end
      
      
          call_this_block { |arg| puts arg.upcase } #---->TWEET
        e.g.
          def call_this_block
            block_result = yield "foo"
            puts block_result
          end
      
      
          call_this_block { |arg| puts arg.reverse } #---->OOF      
        e.g.
          def puts_this_block
            puts yield
          end
          puts_this_block { "tweet" }  #---->tweet
        e.g.
          Bad:
            class Timeline
              def list_tweeks
                @user.friends.each do |friend|
                  friend.tweets.each { |tweet| puts tweet }
                end
              end
              def store_tweeks
                @user.friends.each do |friend|
                  friend.tweets.each { |tweet| tweet.cache }
                end
              end
            end
          Good:
            class Timeline
              def each
                @user.friends.each do |friend|
                  friend.tweets.each { |tweet| yield tweet }
                end
              end
            end
            timeline = Timeline.new(user)
            timeline.each { |tweet| puts tweet }
            timeline.each { |tweet| tweet.cache }
        e.g.
          Bad:
            def update_status(user, tweet)
              begin
                sign_in(user)
                post(tweet)
              rescue ConnectionError => e
                logger.error(e)
              ensure
                sign_out(user)
              end
            end
            def get_list(user, list_name)
              begin
                sign_in(user)
                retrieve_list(list_name)
              rescue ConnectionError => e
                logger.error(e)
              ensure
                sign_out(user)
              end
            end
          Good:
            def while_signed_in_as(user)
              sign_in(user)
              yield
              rescue ConnectionError => e
                logger.error(e)
              ensure
                sign_out(user)
            end
            
            while_signed_in_as(user) do
              post(tweet)
            end
            tweets = while_signed_in_as(user) do
              retrieve_list(list_name)
            end


  • Enumerable:
    •   class Timeline
          def each
            #...
          end
          include Enumerable
        end
      
      
        timeline.sort_by { |tweet| tweet.created_at }
        timeline.map { |tweet| tweet.status }
        timeline.find_all { |tweet| tweet.status =~ /\@csdn/ }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值