From dc331f6ea1ee8058a43d7588e1a612f2172ab078 Mon Sep 17 00:00:00 2001 From: Atsushi Nakatsugawa Date: Fri, 19 May 2017 14:43:41 +0900 Subject: [PATCH 1/2] Clean up client.rb --- .rubocop_todo.yml | 459 +++++++++++++++++++++++++++++++++++++++ examples/data_store.rb | 19 +- examples/file_test.rb | 8 +- examples/performance.rb | 3 +- examples/pointer_test.rb | 1 - examples/signature.rb | 12 +- examples/venue_search.rb | 13 +- lib/ncmb/client.rb | 50 ++--- lib/ncmb/object.rb | 56 ++--- 9 files changed, 540 insertions(+), 81 deletions(-) create mode 100644 .rubocop_todo.yml diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml new file mode 100644 index 0000000..5d1d7a6 --- /dev/null +++ b/.rubocop_todo.yml @@ -0,0 +1,459 @@ +# This configuration was generated by +# `rubocop --auto-gen-config` +# on 2017-05-16 21:52:10 +0900 using RuboCop version 0.48.1. +# The point is for the user to remove these configuration records +# one by one as the offenses are removed from the code base. +# Note that changes in the inspected code, or installation of new +# versions of RuboCop, may require this file to be generated again. + +# Offense count: 1 +# Configuration parameters: AllowSafeAssignment. +Lint/AssignmentInCondition: + Exclude: + - 'examples/user_test.rb' + +# Offense count: 1 +Lint/EmptyWhen: + Exclude: + - 'lib/ncmb/client.rb' + +# Offense count: 3 +# Cop supports --auto-correct. +# Configuration parameters: IgnoreEmptyBlocks, AllowUnusedKeywordArguments. +Lint/UnusedBlockArgument: + Exclude: + - 'lib/ncmb/client.rb' + +# Offense count: 5 +# Cop supports --auto-correct. +# Configuration parameters: AllowUnusedKeywordArguments, IgnoreEmptyMethods. +Lint/UnusedMethodArgument: + Exclude: + - 'lib/ncmb/acl.rb' + - 'lib/ncmb/client.rb' + - 'lib/ncmb/geo_point.rb' + - 'lib/ncmb/increment.rb' + - 'lib/ncmb/relation.rb' + +# Offense count: 5 +Lint/UselessAssignment: + Exclude: + - 'lib/ncmb/client.rb' + - 'lib/ncmb/role.rb' + - 'lib/ncmb/user.rb' + - 'spec/get_spec.rb' + +# Offense count: 2 +Lint/Void: + Exclude: + - 'spec/delete_spec.rb' + +# Offense count: 6 +Metrics/AbcSize: + Max: 70 + +# Offense count: 3 +# Configuration parameters: CountComments. +Metrics/ClassLength: + Max: 177 + +# Offense count: 2 +Metrics/CyclomaticComplexity: + Max: 16 + +# Offense count: 23 +# Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns. +# URISchemes: http, https +Metrics/LineLength: + Max: 122 + +# Offense count: 12 +# Configuration parameters: CountComments. +Metrics/MethodLength: + Max: 68 + +# Offense count: 2 +Metrics/PerceivedComplexity: + Max: 17 + +# Offense count: 3 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles. +# SupportedStyles: prefer_alias, prefer_alias_method +Style/Alias: + Exclude: + - 'lib/ncmb/data_store.rb' + - 'lib/ncmb/file.rb' + - 'lib/ncmb/user.rb' + +# Offense count: 2 +# Cop supports --auto-correct. +Style/AlignArray: + Exclude: + - 'lib/ncmb/push.rb' + +# Offense count: 2 +Style/AsciiComments: + Exclude: + - 'examples/data_store.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +Style/BlockComments: + Exclude: + - 'examples/data_store.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles, ProceduralMethods, FunctionalMethods, IgnoredMethods. +# SupportedStyles: line_count_based, semantic, braces_for_chaining +# ProceduralMethods: benchmark, bm, bmbm, create, each_with_object, measure, new, realtime, tap, with_object +# FunctionalMethods: let, let!, subject, watch +# IgnoredMethods: lambda, proc, it +Style/BlockDelimiters: + Exclude: + - 'lib/ncmb/client.rb' + +# Offense count: 3 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles. +# SupportedStyles: braces, no_braces, context_dependent +Style/BracesAroundHashParameters: + Exclude: + - 'examples/data_store.rb' + - 'examples/performance.rb' + - 'examples/signature.rb' + +# Offense count: 2 +# Cop supports --auto-correct. +Style/ClassMethods: + Exclude: + - 'lib/ncmb/client.rb' + +# Offense count: 12 +Style/ClassVars: + Exclude: + - 'lib/ncmb/client.rb' + - 'lib/ncmb/object.rb' + - 'lib/ncmb/user.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles, SingleLineConditionsOnly, IncludeTernaryExpressions. +# SupportedStyles: assign_to_condition, assign_inside_condition +Style/ConditionalAssignment: + Exclude: + - 'lib/ncmb/role.rb' + +# Offense count: 16 +Style/Documentation: + Exclude: + - 'spec/**/*' + - 'test/**/*' + - 'lib/ncmb/acl.rb' + - 'lib/ncmb/client.rb' + - 'lib/ncmb/data_store.rb' + - 'lib/ncmb/device.rb' + - 'lib/ncmb/file.rb' + - 'lib/ncmb/geo_point.rb' + - 'lib/ncmb/increment.rb' + - 'lib/ncmb/object.rb' + - 'lib/ncmb/push.rb' + - 'lib/ncmb/query.rb' + - 'lib/ncmb/relation.rb' + - 'lib/ncmb/role.rb' + - 'lib/ncmb/user.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles. +# SupportedStyles: compact, expanded +Style/EmptyMethod: + Exclude: + - 'lib/ncmb/relation.rb' + +# Offense count: 3 +# Cop supports --auto-correct. +# Configuration parameters: AllowForAlignment, ForceEqualSignAlignment. +Style/ExtraSpacing: + Exclude: + - 'lib/ncmb/client.rb' + +# Offense count: 5 +# Configuration parameters: MinBodyLength. +Style/GuardClause: + Exclude: + - 'lib/ncmb/acl.rb' + - 'lib/ncmb/data_store.rb' + - 'lib/ncmb/object.rb' + +# Offense count: 5 +# Cop supports --auto-correct. +# Configuration parameters: MaxLineLength. +Style/IfUnlessModifier: + Exclude: + - 'lib/ncmb/acl.rb' + - 'lib/ncmb/data_store.rb' + - 'lib/ncmb/object.rb' + +# Offense count: 2 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles, IndentationWidth. +# SupportedStyles: special_inside_parentheses, consistent, align_braces +Style/IndentHash: + Exclude: + - 'lib/ncmb/acl.rb' + +# Offense count: 3 +# Cop supports --auto-correct. +Style/MethodCallWithoutArgsParentheses: + Exclude: + - 'lib/ncmb/client.rb' + - 'lib/ncmb/role.rb' + - 'spec/delete_spec.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles. +# SupportedStyles: require_parentheses, require_no_parentheses, require_no_parentheses_except_multiline +Style/MethodDefParentheses: + Exclude: + - 'lib/ncmb/data_store.rb' + +# Offense count: 2 +Style/MethodMissing: + Exclude: + - 'lib/ncmb/data_store.rb' + - 'lib/ncmb/object.rb' + +# Offense count: 4 +# Configuration parameters: EnforcedStyle, SupportedStyles. +# SupportedStyles: snake_case, camelCase +Style/MethodName: + Exclude: + - 'lib/ncmb/client.rb' + - 'lib/ncmb/object.rb' + - 'lib/ncmb/query.rb' + - 'lib/ncmb/user.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles. +# SupportedStyles: symmetrical, new_line, same_line +Style/MultilineHashBraceLayout: + Exclude: + - 'lib/ncmb/acl.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: IncludeSemanticChanges. +Style/NonNilCheck: + Exclude: + - 'lib/ncmb/client.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: AutoCorrect, EnforcedStyle, SupportedStyles. +# SupportedStyles: predicate, comparison +Style/NumericPredicate: + Exclude: + - 'spec/**/*' + - 'lib/ncmb/data_store.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: PreferredDelimiters. +Style/PercentLiteralDelimiters: + Exclude: + - 'spec/spec_helper.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles. +# SupportedStyles: short, verbose +Style/PreferredHashMethods: + Exclude: + - 'lib/ncmb/object.rb' + +# Offense count: 3 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles. +# SupportedStyles: compact, exploded +Style/RaiseArgs: + Exclude: + - 'lib/ncmb/client.rb' + - 'lib/ncmb/user.rb' + +# Offense count: 2 +# Cop supports --auto-correct. +# Configuration parameters: AllowMultipleReturnValues. +Style/RedundantReturn: + Exclude: + - 'lib/ncmb/data_store.rb' + - 'lib/ncmb/device.rb' + +# Offense count: 5 +# Cop supports --auto-correct. +Style/RedundantSelf: + Exclude: + - 'lib/ncmb/client.rb' + - 'lib/ncmb/file.rb' + - 'lib/ncmb/object.rb' + - 'lib/ncmb/relation.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +Style/SelfAssignment: + Exclude: + - 'lib/ncmb/client.rb' + +# Offense count: 2 +# Cop supports --auto-correct. +# Configuration parameters: AllowAsExpressionSeparator. +Style/Semicolon: + Exclude: + - 'examples/data_store.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +Style/SpaceAfterComma: + Exclude: + - 'lib/ncmb/client.rb' + +# Offense count: 5 +# Cop supports --auto-correct. +# Configuration parameters: AllowForAlignment. +Style/SpaceAroundOperators: + Exclude: + - 'lib/ncmb/client.rb' + +# Offense count: 4 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles. +# SupportedStyles: space, no_space +Style/SpaceBeforeBlockBraces: + Exclude: + - 'lib/ncmb/client.rb' + +# Offense count: 9 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles, EnforcedStyleForEmptyBraces, SupportedStylesForEmptyBraces, SpaceBeforeBlockParameters. +# SupportedStyles: space, no_space +# SupportedStylesForEmptyBraces: space, no_space +Style/SpaceInsideBlockBraces: + Exclude: + - 'lib/ncmb/client.rb' + +# Offense count: 44 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles, EnforcedStyleForEmptyBraces, SupportedStylesForEmptyBraces. +# SupportedStyles: space, no_space, compact +# SupportedStylesForEmptyBraces: space, no_space +Style/SpaceInsideHashLiteralBraces: + Exclude: + - 'examples/signature.rb' + - 'lib/ncmb/acl.rb' + - 'lib/ncmb/file.rb' + - 'lib/ncmb/query.rb' + - 'lib/ncmb/user.rb' + - 'spec/post_spec.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles. +# SupportedStyles: space, no_space +Style/SpaceInsideStringInterpolation: + Exclude: + - 'lib/ncmb/object.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles. +# SupportedStyles: use_perl_names, use_english_names +Style/SpecialGlobalVars: + Exclude: + - 'ncmb-ruby-client.gemspec' + +# Offense count: 43 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles, ConsistentQuotesInMultiline. +# SupportedStyles: single_quotes, double_quotes +Style/StringLiterals: + Exclude: + - 'Rakefile' + - 'lib/ncmb/acl.rb' + - 'lib/ncmb/client.rb' + - 'lib/ncmb/data_store.rb' + - 'lib/ncmb/device.rb' + +# Offense count: 3 +# Cop supports --auto-correct. +# Configuration parameters: SupportedStyles. +# SupportedStyles: percent, brackets +Style/SymbolArray: + EnforcedStyle: brackets + +# Offense count: 9 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles. +# SupportedStyles: final_newline, final_blank_line +Style/TrailingBlankLines: + Exclude: + - 'Rakefile' + - 'examples/csv_test.rb' + - 'lib/ncmb/error.rb' + - 'lib/ncmb/file.rb' + - 'lib/ncmb/geo_point.rb' + - 'lib/ncmb/increment.rb' + - 'lib/ncmb/relation.rb' + - 'lib/ncmb/user.rb' + - 'spec/spec_helper.rb' + +# Offense count: 2 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyleForMultiline, SupportedStylesForMultiline. +# SupportedStylesForMultiline: comma, consistent_comma, no_comma +Style/TrailingCommaInLiteral: + Exclude: + - 'lib/ncmb/query.rb' + +# Offense count: 77 +# Cop supports --auto-correct. +Style/TrailingWhitespace: + Enabled: false + +# Offense count: 5 +# Cop supports --auto-correct. +# Configuration parameters: ExactNameMatch, AllowPredicates, AllowDSLWriters, IgnoreClassMethods, Whitelist. +# Whitelist: to_ary, to_a, to_c, to_enum, to_h, to_hash, to_i, to_int, to_io, to_open, to_path, to_proc, to_r, to_regexp, to_str, to_s, to_sym +Style/TrivialAccessors: + Exclude: + - 'lib/ncmb/client.rb' + - 'lib/ncmb/data_store.rb' + - 'lib/ncmb/increment.rb' + - 'lib/ncmb/object.rb' + +# Offense count: 2 +# Cop supports --auto-correct. +Style/UnneededPercentQ: + Exclude: + - 'ncmb-ruby-client.gemspec' + +# Offense count: 6 +# Configuration parameters: EnforcedStyle, SupportedStyles. +# SupportedStyles: snake_case, camelCase +Style/VariableName: + Exclude: + - 'examples/acl_test.rb' + - 'examples/performance.rb' + - 'lib/ncmb/data_store.rb' + - 'spec/delete_spec.rb' + - 'spec/get_spec.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, SupportedStyles, MinSize, WordRegex. +# SupportedStyles: percent, brackets +Style/WordArray: + Exclude: + - 'lib/ncmb/data_store.rb' diff --git a/examples/data_store.rb b/examples/data_store.rb index 8bac3c2..b757709 100644 --- a/examples/data_store.rb +++ b/examples/data_store.rb @@ -21,7 +21,7 @@ item.set('Integer', i) item.set('Boolean', true) item.set('Array', [i, i * 2, i * 3, 'Orange', 'Tomato']) - item.set('Object', {test1: 'a', test2: 'b'}) + item.set('Object', { test1: 'a', test2: 'b' }) item.set('Location', NCMB::GeoPoint.new((i + 1) * 10, (i + 2) * 5)) item.set('MultipleLine', "test\ntest\n") item.set('Increment', NCMB::Increment.new(i + 1)) @@ -31,13 +31,15 @@ sleep(2) end -# @todo = @todo.limit(20).where("String", 'テスト100').greaterThan("Integer", 1) -# @todo = @todo.limit(20).notEqualTo("String", 'テスト100') -# @todo = @todo.limit(20).in("String", ['テスト100']) -# @todo = @todo.limit(20).notIn("String", ['テスト100']) -# @todo = @todo.limit(20).inArray("Array", [4]) -# @todo = @todo.limit(20).notInArray("Array", ['Orange']) -# @todo = @todo.limit(20).allInArray("Array", [1, 2, 4]) +=begin +@todo = @todo.limit(20).where("String", 'テスト100').greaterThan("Integer", 1) +@todo = @todo.limit(20).notEqualTo("String", 'テスト100') +@todo = @todo.limit(20).in("String", ['テスト100']) +@todo = @todo.limit(20).notIn("String", ['テスト100']) +@todo = @todo.limit(20).inArray("Array", [4]) +@todo = @todo.limit(20).notInArray("Array", ['Orange']) +@todo = @todo.limit(20).allInArray("Array", [1, 2, 4]) +=end geo1 = NCMB::GeoPoint.new(50, 30); geo2 = NCMB::GeoPoint.new(51, 31); @@ -62,4 +64,3 @@ end # puts "@todo[0].name #{@todo[0].text}" - diff --git a/examples/file_test.rb b/examples/file_test.rb index c8258dc..eeb0eae 100644 --- a/examples/file_test.rb +++ b/examples/file_test.rb @@ -17,19 +17,19 @@ f.acl.public('read', true) f.acl.public('write', true) f.fileName = 'test.png' -f.save() +f.save puts 'Uploaded' f.file = 'http://k.yimg.jp/images/top/sp2/cmn/logo-ns_d_131205.png' -f.update() +f.update puts 'Updated' -f.delete() +f.delete puts 'Deleted' f = NCMB::NFile.new('http://mb.cloud.nifty.com/assets/images/logo.png') f.acl.public('read', true) f.acl.public('write', true) f.fileName = 'test.png' -f.save() +f.save file = NCMB::NFile.new('test.png') fp = open('test.png', 'w') fp.write(file.get) diff --git a/examples/performance.rb b/examples/performance.rb index f8fb6e5..695e47b 100644 --- a/examples/performance.rb +++ b/examples/performance.rb @@ -25,7 +25,7 @@ item.set('Integer', i) item.set('Boolean', true) item.set('Array', [i, i * 2, i * 3, 'Orange', 'Tomato']) - item.set('Object', {test1: 'a', test2: 'b'}) + item.set('Object', { test1: 'a', test2: 'b' }) item.set('Location', NCMB::GeoPoint.new(30, 50)) item.set('MultipleLine', "test\ntest\n") item.set('Increment', NCMB::Increment.new(i + 1)) @@ -41,4 +41,3 @@ end end end - diff --git a/examples/pointer_test.rb b/examples/pointer_test.rb index 318ea84..297229a 100644 --- a/examples/pointer_test.rb +++ b/examples/pointer_test.rb @@ -19,4 +19,3 @@ parent = Parent.new(name: 'Oya') parent.child = child parent.save - diff --git a/examples/signature.rb b/examples/signature.rb index 7bb92db..8a82673 100644 --- a/examples/signature.rb +++ b/examples/signature.rb @@ -13,13 +13,11 @@ ) # puts @client.application_key -puts @client.generate_signature(:get, +puts @client.generate_signature( + :get, '/2013-09-01/classes/TestClass', '2013-12-02T02:44:35.452Z', - { - where: { - testKey: 'testValue' - } - } + { where: { + testKey: 'testValue' + }} ) - diff --git a/examples/venue_search.rb b/examples/venue_search.rb index 2094de7..c64c2f2 100644 --- a/examples/venue_search.rb +++ b/examples/venue_search.rb @@ -7,10 +7,13 @@ require 'ncmb' require 'yaml' yaml = YAML.load_file(File.join(File.dirname(__FILE__), '..', 'setting.yml')) -@ncmb = NCMB.init(application_key: yaml['application_key'], - client_key: yaml['client_key'] - ) -json = JSON.parse(open(File.join(File.dirname(__FILE__), 'venues.json'), 'r').read) +@ncmb = NCMB.init( + application_key: yaml['application_key'], + client_key: yaml['client_key'] +) +content = open(File.join(File.dirname(__FILE__), 'venues.json'), 'r') +json = JSON.parse(content.read) + venues_class = @ncmb.data_store 'Venues' json['response']['venues'].each do |venue| params = { @@ -36,4 +39,4 @@ } # puts venues_class.get params -#puts venues_class.get queries +# puts venues_class.get queries diff --git a/lib/ncmb/client.rb b/lib/ncmb/client.rb index eae6822..69efcba 100644 --- a/lib/ncmb/client.rb +++ b/lib/ncmb/client.rb @@ -60,7 +60,7 @@ def encode_query(queries = {}) results = {} queries.each do |k, v| v = array2hash(v) if v.is_a? Array - value = URI.encode(v.is_a?(Hash) ? v.to_json : v.to_s).gsub("[", "%5B").gsub(":", "%3A").gsub("]", "%5D") + value = URI.encode(v.is_a?(Hash) ? v.to_json : v.to_s).gsub('[', '%5B').gsub(':', '%3A').gsub(']', '%5D') results[k.to_s] = value end results @@ -96,14 +96,14 @@ def hash2query(queries = {}) def generate_signature(method, path, now = nil, queries = {}) params_base = { - "SignatureMethod" => "HmacSHA256", - "SignatureVersion" => "2", - "X-NCMB-Application-Key" => @application_key + 'SignatureMethod' => 'HmacSHA256', + 'SignatureVersion' => '2', + 'X-NCMB-Application-Key' => @application_key } params = method == :get ? params_base.merge(encode_query(queries)) : params_base now ||= Time.now.utc.iso8601 - params = params.merge "X-NCMB-Timestamp" => now - if [].respond_to?("to_h") # Array#to_h inpremented over ruby 2.1 + params = params.merge 'X-NCMB-Timestamp' => now + if [].respond_to?('to_h') # Array#to_h inpremented over ruby 2.1 params = params.sort_by{|a, b| a.to_s}.to_h else sorted_params = {} @@ -116,7 +116,7 @@ def generate_signature(method, path, now = nil, queries = {}) signature_base << method.upcase signature_base << @domain signature_base << path - signature_base << params.collect{|k,v| "#{k}=#{v}"}.join("&") + signature_base << params.collect{|k,v| "#{k}=#{v}"}.join('&') Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), @client_key, signature_base.join("\n"))).strip() end @@ -125,11 +125,11 @@ def make_boundary(boundary, queries) post_body << "--#{boundary}" post_body << "Content-Disposition: form-data; name=\"file\"; filename=\"#{queries[:fileName]}\"" post_body << "Content-Type: #{queries['mime-type'.to_sym]}" - post_body << "" + post_body << '' post_body << queries[:file].read - post_body << "" + post_body << '' post_body << "--#{boundary}" - post_body << "Content-Disposition: form-data; name=\"acl\"" + post_body << 'Content-Disposition: form-data; name="acl"' post_body << "" post_body << queries[:acl].to_json post_body << "--#{boundary}--" @@ -142,10 +142,10 @@ def request(method, path, queries = {}) http = Net::HTTP.new(@domain, 443) http.use_ssl=true headers = { - "X-NCMB-Application-Key" => @application_key, - "X-NCMB-Signature" => signature, - "X-NCMB-Timestamp" => now, - "Content-Type" => 'application/json' + 'X-NCMB-Application-Key' => @application_key, + 'X-NCMB-Signature' => signature, + 'X-NCMB-Timestamp' => now, + 'Content-Type' => 'application/json' } if NCMB.CurrentUser headers['X-NCMB-Apps-Session-Token'] = NCMB.CurrentUser.sessionToken @@ -158,7 +158,7 @@ def request(method, path, queries = {}) query = encode_query(queries).map do |key, value| "#{key}=#{value}" end.join("&") - path = path + (query == '' ? "" : "?"+query) + path = path + (query == '' ? '' : "?"+query) rp = Regexp.new "/#{NCMB::API_VERSION}/files/.*" if path =~ rp json = http.get(path, headers).body @@ -170,7 +170,7 @@ def request(method, path, queries = {}) if queries[:file].is_a?(File) || queries[:file].is_a?(StringIO) boundary = SecureRandom.uuid req.body = make_boundary(boundary, queries) - headers["Content-Type"] = "multipart/form-data; boundary=#{boundary}" + headers['Content-Type'] = "multipart/form-data; boundary=#{boundary}" else queries = change_query(queries) req.body = queries.to_json @@ -184,7 +184,7 @@ def request(method, path, queries = {}) if queries[:file].is_a?(File) || queries[:file].is_a?(StringIO) boundary = SecureRandom.uuid req.body = make_boundary(boundary, queries) - headers["Content-Type"] = "multipart/form-data; boundary=#{boundary}" + headers['Content-Type'] = "multipart/form-data; boundary=#{boundary}" else queries = change_query(queries) req.body = queries.to_json @@ -195,7 +195,7 @@ def request(method, path, queries = {}) json = JSON.parse(http.request(req).body, symbolize_names: true) when :delete response = http.delete(path, headers).body - return true if response == "" + return true if response == '' json = JSON.parse(response, symbolize_names: true) end rescue => e @@ -209,26 +209,24 @@ def request(method, path, queries = {}) end end - def NCMB.initialize(params = {}) + def self.initialize(params = {}) defaulted = { - application_key: ENV["NCMB_APPLICATION_KEY"], - client_key: ENV["NCMB_CLIENT_KEY"] + application_key: ENV['NCMB_APPLICATION_KEY'], + client_key: ENV['NCMB_CLIENT_KEY'] } defaulted.merge!(params) @@client = Client.new(defaulted) end - def NCMB.CurrentUser + def self.current_user @@current_user end + # Error class of NCMB class APIError < StandardError + attr_accessor :message def initialize(msg) @message = msg end - - def message - @message - end end end diff --git a/lib/ncmb/object.rb b/lib/ncmb/object.rb index 5ca0ed5..109886d 100644 --- a/lib/ncmb/object.rb +++ b/lib/ncmb/object.rb @@ -5,19 +5,19 @@ class Object include NCMB def initialize(name, fields = {}) - @name = name + @name = name fields[:acl] = NCMB::Acl.new(fields[:acl]) - @fields = fields + @fields = fields end - + def fields @fields end - + def ClassName @name end - + def method_missing(name, value = nil) if name =~ /.*=$/ sym = name.to_s.gsub(/(.*?)=$/, '\1').to_sym @@ -35,37 +35,37 @@ def method_missing(name, value = nil) def set(name, value) @fields[name.to_sym] = value end - + def call(name) @fields[name.to_sym] || NoMethodError end - + def [](key) @fields[key] end - + def deletable? - if self.acl['*'.to_sym][:write] == true + if acl['*'.to_sym][:write] == true return true end return false unless NCMB.CurrentUser - return false unless self.acl[NCMB.CurrentUser.objectId.to_sym] - return false unless self.acl[NCMB.CurrentUser.objectId.to_sym][:write] + return false unless acl[NCMB.CurrentUser.objectId.to_sym] + return false unless acl[NCMB.CurrentUser.objectId.to_sym][:write] true end - + def base_path "/#{@@client.api_version}/classes/#{@name}" end - + def path "#{base_path}/#{@fields[:objectId] || '' }" end - + def saved? @fields[:objectId] != nil end - + def convert_params @fields.each do |key, field| if field.is_a?(NCMB::Object) @@ -77,16 +77,18 @@ def convert_params } end if field.is_a?(Array) && field[0].is_a?(NCMB::Object) - relation = NCMB::Relation.new - field.each do |sub_field| - sub_field.save unless sub_field.saved? - relation << sub_field - end - @fields[key] = relation + else + next + end + relation = NCMB::Relation.new + field.each do |sub_field| + sub_field.save unless sub_field.saved? + relation << sub_field end + @fields[key] = relation end end - + def post return self.put if saved? convert_params @@ -94,8 +96,8 @@ def post @fields.merge!(result) self end - alias :save :post - + alias save post + def put return self.post unless saved? convert_params @@ -108,8 +110,8 @@ def put @fields[:updateDate] = result[:updateDate] self end - alias :update :put - + alias update put + def delete response = @@client.delete path, {} if response == true @@ -119,7 +121,7 @@ def delete return false end end - + def error @@last_error end From faad4354a697506c66f9b927dd484fda76e81682 Mon Sep 17 00:00:00 2001 From: Atsushi Nakatsugawa Date: Fri, 19 May 2017 15:01:22 +0900 Subject: [PATCH 2/2] Clean up client.rb --- lib/ncmb/client.rb | 66 ++++++++++++++++++++++++++++++---------------- 1 file changed, 44 insertions(+), 22 deletions(-) diff --git a/lib/ncmb/client.rb b/lib/ncmb/client.rb index 69efcba..905aaa9 100644 --- a/lib/ncmb/client.rb +++ b/lib/ncmb/client.rb @@ -52,7 +52,7 @@ def array2hash(ary) new_v = [hash] end end - new_v = new_v.sort_by{|a, b| a.to_s}.to_h + new_v = new_v.sort_by{ |a, b| a.to_s }.to_h new_v end @@ -60,7 +60,11 @@ def encode_query(queries = {}) results = {} queries.each do |k, v| v = array2hash(v) if v.is_a? Array - value = URI.encode(v.is_a?(Hash) ? v.to_json : v.to_s).gsub('[', '%5B').gsub(':', '%3A').gsub(']', '%5D') + value = URI.encode(v.is_a?(Hash) ? v.to_json : v.to_s) + .encode("UTF-8") + .gsub('[', '%5B') + .gsub(':', '%3A') + .gsub(']', '%5D') results[k.to_s] = value end results @@ -81,7 +85,6 @@ def hash2query(queries = {}) results = {} queries.each do |k, v| # v = array2hash(v) if v.is_a? Array - puts "#{k} -> #{v.class}" case v when Hash, TrueClass, FalseClass, Array then results[k.to_s] = v @@ -90,7 +93,6 @@ def hash2query(queries = {}) results[k.to_s] = v.to_s end end - puts results results end @@ -104,10 +106,10 @@ def generate_signature(method, path, now = nil, queries = {}) now ||= Time.now.utc.iso8601 params = params.merge 'X-NCMB-Timestamp' => now if [].respond_to?('to_h') # Array#to_h inpremented over ruby 2.1 - params = params.sort_by{|a, b| a.to_s}.to_h + params = params.sort_by { |a, b| a.to_s }.to_h else sorted_params = {} - params = params.sort_by{|a, b| a.to_s}.each {|kv| + params = params.sort_by { |a, b| a.to_s }.each { |kv| sorted_params[kv[0]] = kv[1] } params = sorted_params @@ -116,21 +118,27 @@ def generate_signature(method, path, now = nil, queries = {}) signature_base << method.upcase signature_base << @domain signature_base << path - signature_base << params.collect{|k,v| "#{k}=#{v}"}.join('&') - Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), @client_key, signature_base.join("\n"))).strip() + signature_base << params.collect { |k, v| "#{k}=#{v}" }.join('&') + Base64.encode64( + OpenSSL::HMAC.digest(OpenSSL::Digest.new('sha256'), + @client_key, + signature_base.join("\n")) + ).strip end def make_boundary(boundary, queries) + content_disposition = 'Content-Disposition: form-data; name=\"file\"; ' + content_disposition += "filename=\"#{queries[:fileName]}\"" post_body = [] post_body << "--#{boundary}" - post_body << "Content-Disposition: form-data; name=\"file\"; filename=\"#{queries[:fileName]}\"" + post_body << content_disposition post_body << "Content-Type: #{queries['mime-type'.to_sym]}" post_body << '' post_body << queries[:file].read post_body << '' post_body << "--#{boundary}" post_body << 'Content-Disposition: form-data; name="acl"' - post_body << "" + post_body << '' post_body << queries[:acl].to_json post_body << "--#{boundary}--" post_body.join("\r\n") @@ -140,7 +148,7 @@ def request(method, path, queries = {}) now = Time.now.utc.iso8601 signature = generate_signature(method, path, now, queries) http = Net::HTTP.new(@domain, 443) - http.use_ssl=true + http.use_ssl = true headers = { 'X-NCMB-Application-Key' => @application_key, 'X-NCMB-Signature' => signature, @@ -157,20 +165,24 @@ def request(method, path, queries = {}) when :get query = encode_query(queries).map do |key, value| "#{key}=#{value}" - end.join("&") - path = path + (query == '' ? '' : "?"+query) + end.join('&') + path += (query == '' ? '' : '?' + query) rp = Regexp.new "/#{NCMB::API_VERSION}/files/.*" if path =~ rp json = http.get(path, headers).body else - json = JSON.parse(http.get(path, headers).body, symbolize_names: true) + json = JSON.parse( + http.get(path, headers).body, + symbolize_names: true + ) end when :post req = Net::HTTP::Post.new(path) if queries[:file].is_a?(File) || queries[:file].is_a?(StringIO) boundary = SecureRandom.uuid req.body = make_boundary(boundary, queries) - headers['Content-Type'] = "multipart/form-data; boundary=#{boundary}" + content_type = "multipart/form-data; boundary=#{boundary}" + headers['Content-Type'] = content_type else queries = change_query(queries) req.body = queries.to_json @@ -178,13 +190,17 @@ def request(method, path, queries = {}) headers.each do |key, value| req[key] = value end - json = JSON.parse(http.request(req).body, symbolize_names: true) + json = JSON.parse( + http.request(req).body, + symbolize_names: true + ) when :put req = Net::HTTP::Put.new(path) if queries[:file].is_a?(File) || queries[:file].is_a?(StringIO) boundary = SecureRandom.uuid req.body = make_boundary(boundary, queries) - headers['Content-Type'] = "multipart/form-data; boundary=#{boundary}" + content_type = "multipart/form-data; boundary=#{boundary}" + headers['Content-Type'] = content_type else queries = change_query(queries) req.body = queries.to_json @@ -192,17 +208,23 @@ def request(method, path, queries = {}) headers.each do |key, value| req[key] = value end - json = JSON.parse(http.request(req).body, symbolize_names: true) + json = JSON.parse( + http.request(req).body, + symbolize_names: true + ) when :delete response = http.delete(path, headers).body return true if response == '' - json = JSON.parse(response, symbolize_names: true) + json = JSON.parse( + response, + symbolize_names: true + ) end rescue => e - @@last_error = e + @@last_error = e raise NCMB::APIError.new(e.to_s) end - if json.is_a?(Hash) && json[:error] != nil + if json.is_a?(Hash) && !json[:error].nil? raise NCMB::APIError.new(json[:error]) end json @@ -217,7 +239,7 @@ def self.initialize(params = {}) defaulted.merge!(params) @@client = Client.new(defaulted) end - + def self.current_user @@current_user end