Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clean up client.rb #24

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
459 changes: 459 additions & 0 deletions .rubocop_todo.yml

Large diffs are not rendered by default.

19 changes: 10 additions & 9 deletions examples/data_store.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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' })
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[rubocop]

  • Redundant curly braces around a hash parameter.

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))
Expand All @@ -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
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[rubocop]

  • Do not use block comments. :ref
  • Use only ascii symbols in comments. :ref

@todo = @todo.limit(20).where("String", 'テスト100').greaterThan("Integer", 1)
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[rubocop]

  • Use only ascii symbols in comments. :ref

@todo = @todo.limit(20).notEqualTo("String", 'テスト100')
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[rubocop]

  • Use only ascii symbols in comments. :ref

@todo = @todo.limit(20).in("String", ['テスト100'])
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[rubocop]

  • Use only ascii symbols in comments. :ref

@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);
Expand All @@ -62,4 +64,3 @@
end

# puts "@todo[0].name #{@todo[0].text}"

8 changes: 4 additions & 4 deletions examples/file_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 1 addition & 2 deletions examples/performance.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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' })
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[rubocop]

  • Redundant curly braces around a hash parameter.

item.set('Location', NCMB::GeoPoint.new(30, 50))
item.set('MultipleLine', "test\ntest\n")
item.set('Increment', NCMB::Increment.new(i + 1))
Expand All @@ -41,4 +41,3 @@
end
end
end

1 change: 0 additions & 1 deletion examples/pointer_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,3 @@
parent = Parent.new(name: 'Oya')
parent.child = child
parent.save

12 changes: 5 additions & 7 deletions examples/signature.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[rubocop]

  • Redundant curly braces around a hash parameter.

testKey: 'testValue'
}}
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[rubocop]

  • Space inside } missing. :ref

)

13 changes: 8 additions & 5 deletions examples/venue_search.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand All @@ -36,4 +39,4 @@
}
#
puts venues_class.get params
#puts venues_class.get queries
# puts venues_class.get queries
106 changes: 63 additions & 43 deletions lib/ncmb/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,19 @@ 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
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[rubocop]

  • Space missing to the left of {.
  • Unused block argument - b. If it's necessary, use _ or _b as an argument name to indicate that it won't be used. :ref

new_v
end

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")
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[rubocop]

  • Align .encode with .encode on line 63.
  • Prefer single-quoted strings when you don't need string interpolation or special symbols. :ref

.gsub('[', '%5B')
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[rubocop]

  • Align .gsub with .encode on line 63.

.gsub(':', '%3A')
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[rubocop]

  • Align .gsub with .encode on line 63.

.gsub(']', '%5D')
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[rubocop]

  • Align .gsub with .encode on line 63.

results[k.to_s] = value
end
results
Expand All @@ -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
Expand All @@ -90,24 +93,23 @@ def hash2query(queries = {})
results[k.to_s] = v.to_s
end
end
puts results
results
end

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.sort_by{|a, b| a.to_s}.to_h
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
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[rubocop]

  • Unused block argument - b. If it's necessary, use _ or _b as an argument name to indicate that it won't be used. :ref

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|
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[rubocop]

  • Useless assignment to variable - params. :ref
  • Unused block argument - b. If it's necessary, use _ or _b as an argument name to indicate that it won't be used. :ref
  • Avoid using {...} for multi-line blocks. :ref

sorted_params[kv[0]] = kv[1]
}
params = sorted_params
Expand All @@ -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,
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[rubocop]

  • Align the parameters of a method call if they span more than one line. :ref

signature_base.join("\n"))
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[rubocop]

  • Align the parameters of a method call if they span more than one line. :ref

).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 << ''
post_body << queries[:file].read
post_body << ""
post_body << ''
post_body << "--#{boundary}"
post_body << "Content-Disposition: form-data; name=\"acl\""
post_body << ""
post_body << 'Content-Disposition: form-data; name="acl"'
post_body << ''
post_body << queries[:acl].to_json
post_body << "--#{boundary}--"
post_body.join("\r\n")
Expand All @@ -140,12 +148,12 @@ 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,
"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
Expand All @@ -157,78 +165,90 @@ 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(
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[rubocop]

  • Use 2 (not -5) spaces for indentation. :ref

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
end
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
end
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)
return true if response == ''
json = JSON.parse(
response,
symbolize_names: true
)
end
rescue => e
@@last_error = e
@@last_error = e
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[rubocop]

  • Replace class var @@last_error with a class instance var. :ref

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
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
Loading