id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
900
matiasgagliano/action_access
lib/action_access/user_utilities.rb
ActionAccess.UserUtilities.can?
def can?(action, resource, options = {}) keeper = ActionAccess::Keeper.instance clearance_levels = Array(clearance_levels()) clearance_levels.any? { |c| keeper.lets? c, action, resource, options } end
ruby
def can?(action, resource, options = {}) keeper = ActionAccess::Keeper.instance clearance_levels = Array(clearance_levels()) clearance_levels.any? { |c| keeper.lets? c, action, resource, options } end
[ "def", "can?", "(", "action", ",", "resource", ",", "options", "=", "{", "}", ")", "keeper", "=", "ActionAccess", "::", "Keeper", ".", "instance", "clearance_levels", "=", "Array", "(", "clearance_levels", "(", ")", ")", "clearance_levels", ".", "any?", "{", "|", "c", "|", "keeper", ".", "lets?", "c", ",", "action", ",", "resource", ",", "options", "}", "end" ]
Check if the user is authorized to perform a given action. Resource can be either plural or singular. == Examples: user.can? :show, :articles user.can? :show, @article user.can? :show, ArticlesController # True if any of the user's clearance levels allows to access 'articles#show' user.can? :edit, :articles, namespace: :admin user.can? :edit, @admin_article user.can? :edit, Admin::ArticlesController # True if any of the user's clearance levels allows to access 'admin/articles#edit'
[ "Check", "if", "the", "user", "is", "authorized", "to", "perform", "a", "given", "action", ".", "Resource", "can", "be", "either", "plural", "or", "singular", "." ]
aa1db07489943e2d5f281fd76257884f52de9766
https://github.com/matiasgagliano/action_access/blob/aa1db07489943e2d5f281fd76257884f52de9766/lib/action_access/user_utilities.rb#L18-L22
901
ssut/telegram-rb
lib/telegram/models.rb
Telegram.TelegramBase.send_image
def send_image(path, refer, &callback) if @type == 'encr_chat' logger.warn("Currently telegram-cli has a bug with send_typing, then prevent this for safety") return end fail_back(&callback) if not File.exist?(path) @client.send_photo(targetize, path, &callback) end
ruby
def send_image(path, refer, &callback) if @type == 'encr_chat' logger.warn("Currently telegram-cli has a bug with send_typing, then prevent this for safety") return end fail_back(&callback) if not File.exist?(path) @client.send_photo(targetize, path, &callback) end
[ "def", "send_image", "(", "path", ",", "refer", ",", "&", "callback", ")", "if", "@type", "==", "'encr_chat'", "logger", ".", "warn", "(", "\"Currently telegram-cli has a bug with send_typing, then prevent this for safety\"", ")", "return", "end", "fail_back", "(", "callback", ")", "if", "not", "File", ".", "exist?", "(", "path", ")", "@client", ".", "send_photo", "(", "targetize", ",", "path", ",", "callback", ")", "end" ]
Send an image @param [String] path The absoulte path of the image you want to send @param [TelegramMessage] refer referral of the method call @param [Block] callback Callback block that will be called when finished @since [0.1.1]
[ "Send", "an", "image" ]
2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2
https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/models.rb#L93-L100
902
ssut/telegram-rb
lib/telegram/models.rb
Telegram.TelegramBase.send_image_url
def send_image_url(url, opt, refer, &callback) begin opt = {} if opt.nil? http = EM::HttpRequest.new(url, :connect_timeout => 2, :inactivity_timeout => 5).get opt file = Tempfile.new(['image', 'jpg']) http.stream { |chunk| file.write(chunk) } http.callback { file.close type = FastImage.type(file.path) if %i(jpeg png gif).include?(type) send_image(file.path, refer, &callback) else fail_back(&callback) end } rescue Exception => e logger.error("An error occurred during the image downloading: #{e.inspect} #{e.backtrace}") fail_back(&callback) end end
ruby
def send_image_url(url, opt, refer, &callback) begin opt = {} if opt.nil? http = EM::HttpRequest.new(url, :connect_timeout => 2, :inactivity_timeout => 5).get opt file = Tempfile.new(['image', 'jpg']) http.stream { |chunk| file.write(chunk) } http.callback { file.close type = FastImage.type(file.path) if %i(jpeg png gif).include?(type) send_image(file.path, refer, &callback) else fail_back(&callback) end } rescue Exception => e logger.error("An error occurred during the image downloading: #{e.inspect} #{e.backtrace}") fail_back(&callback) end end
[ "def", "send_image_url", "(", "url", ",", "opt", ",", "refer", ",", "&", "callback", ")", "begin", "opt", "=", "{", "}", "if", "opt", ".", "nil?", "http", "=", "EM", "::", "HttpRequest", ".", "new", "(", "url", ",", ":connect_timeout", "=>", "2", ",", ":inactivity_timeout", "=>", "5", ")", ".", "get", "opt", "file", "=", "Tempfile", ".", "new", "(", "[", "'image'", ",", "'jpg'", "]", ")", "http", ".", "stream", "{", "|", "chunk", "|", "file", ".", "write", "(", "chunk", ")", "}", "http", ".", "callback", "{", "file", ".", "close", "type", "=", "FastImage", ".", "type", "(", "file", ".", "path", ")", "if", "%i(", "jpeg", "png", "gif", ")", ".", "include?", "(", "type", ")", "send_image", "(", "file", ".", "path", ",", "refer", ",", "callback", ")", "else", "fail_back", "(", "callback", ")", "end", "}", "rescue", "Exception", "=>", "e", "logger", ".", "error", "(", "\"An error occurred during the image downloading: #{e.inspect} #{e.backtrace}\"", ")", "fail_back", "(", "callback", ")", "end", "end" ]
Send an image with given url, not implemen @param [String] url The URL of the image you want to send @param [TelegramMessage] refer referral of the method call @param [Block] callback Callback block that will be called when finished @since [0.1.1]
[ "Send", "an", "image", "with", "given", "url", "not", "implemen" ]
2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2
https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/models.rb#L108-L129
903
ssut/telegram-rb
lib/telegram/models.rb
Telegram.TelegramBase.send_video
def send_video(path, refer, &callback) fail_back(&callback) if not File.exist?(path) @client.send_video(targetize, path, &callback) end
ruby
def send_video(path, refer, &callback) fail_back(&callback) if not File.exist?(path) @client.send_video(targetize, path, &callback) end
[ "def", "send_video", "(", "path", ",", "refer", ",", "&", "callback", ")", "fail_back", "(", "callback", ")", "if", "not", "File", ".", "exist?", "(", "path", ")", "@client", ".", "send_video", "(", "targetize", ",", "path", ",", "callback", ")", "end" ]
Send a video @param [String] path The absoulte path of the video you want to send @param [TelegramMessage] refer referral of the method call @param [Block] callback Callback block that will be called when finished @since [0.1.1]
[ "Send", "a", "video" ]
2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2
https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/models.rb#L137-L140
904
ssut/telegram-rb
lib/telegram/models.rb
Telegram.TelegramMessage.reply
def reply(type, content, target=nil, &callback) target = @target if target.nil? case type when :text target.send_message(content, self, &callback) when :image option = nil content, option = content if content.class == Array if content.include?('http') target.method(:send_image_url).call(content, option, self, &callback) else target.method(:send_image).call(content, self, &callback) end when :video target.send_video(content, self, &callback) end end
ruby
def reply(type, content, target=nil, &callback) target = @target if target.nil? case type when :text target.send_message(content, self, &callback) when :image option = nil content, option = content if content.class == Array if content.include?('http') target.method(:send_image_url).call(content, option, self, &callback) else target.method(:send_image).call(content, self, &callback) end when :video target.send_video(content, self, &callback) end end
[ "def", "reply", "(", "type", ",", "content", ",", "target", "=", "nil", ",", "&", "callback", ")", "target", "=", "@target", "if", "target", ".", "nil?", "case", "type", "when", ":text", "target", ".", "send_message", "(", "content", ",", "self", ",", "callback", ")", "when", ":image", "option", "=", "nil", "content", ",", "option", "=", "content", "if", "content", ".", "class", "==", "Array", "if", "content", ".", "include?", "(", "'http'", ")", "target", ".", "method", "(", ":send_image_url", ")", ".", "call", "(", "content", ",", "option", ",", "self", ",", "callback", ")", "else", "target", ".", "method", "(", ":send_image", ")", ".", "call", "(", "content", ",", "self", ",", "callback", ")", "end", "when", ":video", "target", ".", "send_video", "(", "content", ",", "self", ",", "callback", ")", "end", "end" ]
Reply a message to the chat @param [Symbol] type Type of the message (either of :text, :sticker, :image) @param [String] content Content to send a message @param [TelegramChat] target Specify a TelegramChat to send @param [TelegramContact] target Specify a TelegramContact to send @param [Block] callback Callback block that will be called when finished @since [0.1.0]
[ "Reply", "a", "message", "to", "the", "chat" ]
2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2
https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/models.rb#L334-L351
905
ssut/telegram-rb
lib/telegram/api.rb
Telegram.API.update!
def update!(&cb) done = false EM.synchrony do multi = EM::Synchrony::Multi.new multi.add :profile, update_profile! multi.add :contacts, update_contacts! multi.add :chats, update_chats! multi.perform done = true end check_done = Proc.new { if done @starts_at = Time.now cb.call unless cb.nil? logger.info("Successfully loaded all information") else EM.next_tick(&check_done) end } EM.add_timer(0, &check_done) end
ruby
def update!(&cb) done = false EM.synchrony do multi = EM::Synchrony::Multi.new multi.add :profile, update_profile! multi.add :contacts, update_contacts! multi.add :chats, update_chats! multi.perform done = true end check_done = Proc.new { if done @starts_at = Time.now cb.call unless cb.nil? logger.info("Successfully loaded all information") else EM.next_tick(&check_done) end } EM.add_timer(0, &check_done) end
[ "def", "update!", "(", "&", "cb", ")", "done", "=", "false", "EM", ".", "synchrony", "do", "multi", "=", "EM", "::", "Synchrony", "::", "Multi", ".", "new", "multi", ".", "add", ":profile", ",", "update_profile!", "multi", ".", "add", ":contacts", ",", "update_contacts!", "multi", ".", "add", ":chats", ",", "update_chats!", "multi", ".", "perform", "done", "=", "true", "end", "check_done", "=", "Proc", ".", "new", "{", "if", "done", "@starts_at", "=", "Time", ".", "now", "cb", ".", "call", "unless", "cb", ".", "nil?", "logger", ".", "info", "(", "\"Successfully loaded all information\"", ")", "else", "EM", ".", "next_tick", "(", "check_done", ")", "end", "}", "EM", ".", "add_timer", "(", "0", ",", "check_done", ")", "end" ]
Update user profile, contacts and chats @api private
[ "Update", "user", "profile", "contacts", "and", "chats" ]
2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2
https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/api.rb#L11-L32
906
ssut/telegram-rb
lib/telegram/api.rb
Telegram.API.update_profile!
def update_profile! assert! callback = Callback.new @profile = nil @connection.communicate('get_self') do |success, data| if success callback.trigger(:success) contact = TelegramContact.pick_or_new(self, data) @contacts << contact unless self.contacts.include?(contact) @profile = contact else raise "Couldn't fetch the user profile." end end callback end
ruby
def update_profile! assert! callback = Callback.new @profile = nil @connection.communicate('get_self') do |success, data| if success callback.trigger(:success) contact = TelegramContact.pick_or_new(self, data) @contacts << contact unless self.contacts.include?(contact) @profile = contact else raise "Couldn't fetch the user profile." end end callback end
[ "def", "update_profile!", "assert!", "callback", "=", "Callback", ".", "new", "@profile", "=", "nil", "@connection", ".", "communicate", "(", "'get_self'", ")", "do", "|", "success", ",", "data", "|", "if", "success", "callback", ".", "trigger", "(", ":success", ")", "contact", "=", "TelegramContact", ".", "pick_or_new", "(", "self", ",", "data", ")", "@contacts", "<<", "contact", "unless", "self", ".", "contacts", ".", "include?", "(", "contact", ")", "@profile", "=", "contact", "else", "raise", "\"Couldn't fetch the user profile.\"", "end", "end", "callback", "end" ]
Update user profile @api private
[ "Update", "user", "profile" ]
2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2
https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/api.rb#L37-L52
907
ssut/telegram-rb
lib/telegram/api.rb
Telegram.API.update_contacts!
def update_contacts! assert! callback = Callback.new @contacts = [] @connection.communicate('contact_list') do |success, data| if success and data.class == Array callback.trigger(:success) data.each { |contact| contact = TelegramContact.pick_or_new(self, contact) @contacts << contact unless self.contacts.include?(contact) } else raise "Couldn't fetch the contact list." end end callback end
ruby
def update_contacts! assert! callback = Callback.new @contacts = [] @connection.communicate('contact_list') do |success, data| if success and data.class == Array callback.trigger(:success) data.each { |contact| contact = TelegramContact.pick_or_new(self, contact) @contacts << contact unless self.contacts.include?(contact) } else raise "Couldn't fetch the contact list." end end callback end
[ "def", "update_contacts!", "assert!", "callback", "=", "Callback", ".", "new", "@contacts", "=", "[", "]", "@connection", ".", "communicate", "(", "'contact_list'", ")", "do", "|", "success", ",", "data", "|", "if", "success", "and", "data", ".", "class", "==", "Array", "callback", ".", "trigger", "(", ":success", ")", "data", ".", "each", "{", "|", "contact", "|", "contact", "=", "TelegramContact", ".", "pick_or_new", "(", "self", ",", "contact", ")", "@contacts", "<<", "contact", "unless", "self", ".", "contacts", ".", "include?", "(", "contact", ")", "}", "else", "raise", "\"Couldn't fetch the contact list.\"", "end", "end", "callback", "end" ]
Update user contacts @api private
[ "Update", "user", "contacts" ]
2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2
https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/api.rb#L57-L73
908
ssut/telegram-rb
lib/telegram/api.rb
Telegram.API.update_chats!
def update_chats! assert! callback = Callback.new collected = 0 collect_done = Proc.new do |id, data, count| collected += 1 @chats << TelegramChat.new(self, data) callback.trigger(:success) if collected == count end collect = Proc.new do |id, count| @connection.communicate(['chat_info', "chat\##{id}"]) do |success, data| collect_done.call(id, data, count) if success end end @chats = [] @connection.communicate('dialog_list') do |success, data| if success and data.class == Array chatsize = data.count { |chat| chat['peer_type'] == 'chat' } data.each do |chat| if chat['peer_type'] == 'chat' collect.call(chat['peer_id'], chatsize) elsif chat['peer_type'] == 'user' @chats << TelegramChat.new(self, chat) end end callback.trigger(:success) if chatsize == 0 else raise "Couldn't fetch the dialog(chat) list." end end callback end
ruby
def update_chats! assert! callback = Callback.new collected = 0 collect_done = Proc.new do |id, data, count| collected += 1 @chats << TelegramChat.new(self, data) callback.trigger(:success) if collected == count end collect = Proc.new do |id, count| @connection.communicate(['chat_info', "chat\##{id}"]) do |success, data| collect_done.call(id, data, count) if success end end @chats = [] @connection.communicate('dialog_list') do |success, data| if success and data.class == Array chatsize = data.count { |chat| chat['peer_type'] == 'chat' } data.each do |chat| if chat['peer_type'] == 'chat' collect.call(chat['peer_id'], chatsize) elsif chat['peer_type'] == 'user' @chats << TelegramChat.new(self, chat) end end callback.trigger(:success) if chatsize == 0 else raise "Couldn't fetch the dialog(chat) list." end end callback end
[ "def", "update_chats!", "assert!", "callback", "=", "Callback", ".", "new", "collected", "=", "0", "collect_done", "=", "Proc", ".", "new", "do", "|", "id", ",", "data", ",", "count", "|", "collected", "+=", "1", "@chats", "<<", "TelegramChat", ".", "new", "(", "self", ",", "data", ")", "callback", ".", "trigger", "(", ":success", ")", "if", "collected", "==", "count", "end", "collect", "=", "Proc", ".", "new", "do", "|", "id", ",", "count", "|", "@connection", ".", "communicate", "(", "[", "'chat_info'", ",", "\"chat\\##{id}\"", "]", ")", "do", "|", "success", ",", "data", "|", "collect_done", ".", "call", "(", "id", ",", "data", ",", "count", ")", "if", "success", "end", "end", "@chats", "=", "[", "]", "@connection", ".", "communicate", "(", "'dialog_list'", ")", "do", "|", "success", ",", "data", "|", "if", "success", "and", "data", ".", "class", "==", "Array", "chatsize", "=", "data", ".", "count", "{", "|", "chat", "|", "chat", "[", "'peer_type'", "]", "==", "'chat'", "}", "data", ".", "each", "do", "|", "chat", "|", "if", "chat", "[", "'peer_type'", "]", "==", "'chat'", "collect", ".", "call", "(", "chat", "[", "'peer_id'", "]", ",", "chatsize", ")", "elsif", "chat", "[", "'peer_type'", "]", "==", "'user'", "@chats", "<<", "TelegramChat", ".", "new", "(", "self", ",", "chat", ")", "end", "end", "callback", ".", "trigger", "(", ":success", ")", "if", "chatsize", "==", "0", "else", "raise", "\"Couldn't fetch the dialog(chat) list.\"", "end", "end", "callback", "end" ]
Update user chats @api private
[ "Update", "user", "chats" ]
2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2
https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/api.rb#L78-L111
909
ssut/telegram-rb
lib/telegram/api.rb
Telegram.API.send_contact
def send_contact(peer, phone, first_name, last_name) assert! @connection.communicate(['send_contact', peer, phone, first_name, last_name]) end
ruby
def send_contact(peer, phone, first_name, last_name) assert! @connection.communicate(['send_contact', peer, phone, first_name, last_name]) end
[ "def", "send_contact", "(", "peer", ",", "phone", ",", "first_name", ",", "last_name", ")", "assert!", "@connection", ".", "communicate", "(", "[", "'send_contact'", ",", "peer", ",", "phone", ",", "first_name", ",", "last_name", "]", ")", "end" ]
Send contact to peer chat @param [String] peer Target chat to which contact will be send @param [String] contact phone number @param [String] contact first name @param [String] contact last name @example telegram.send_contact('chat#1234567', '9329232332', 'Foo', 'Bar')
[ "Send", "contact", "to", "peer", "chat" ]
2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2
https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/api.rb#L202-L205
910
ssut/telegram-rb
lib/telegram/api.rb
Telegram.API.download_attachment
def download_attachment(type, seq, &callback) assert! raise "Type mismatch" unless %w(photo video audio).include?(type) @connection.communicate(["load_#{type.to_s}", seq], &callback) end
ruby
def download_attachment(type, seq, &callback) assert! raise "Type mismatch" unless %w(photo video audio).include?(type) @connection.communicate(["load_#{type.to_s}", seq], &callback) end
[ "def", "download_attachment", "(", "type", ",", "seq", ",", "&", "callback", ")", "assert!", "raise", "\"Type mismatch\"", "unless", "%w(", "photo", "video", "audio", ")", ".", "include?", "(", "type", ")", "@connection", ".", "communicate", "(", "[", "\"load_#{type.to_s}\"", ",", "seq", "]", ",", "callback", ")", "end" ]
Download an attachment from a message @param [type] type The type of an attachment (:photo, :video, :audio) @param [String] seq Message sequence number @param [Block] callback Callback block that will be called when finished @yieldparam [Bool] success The result of the request (true or false) @yieldparam [Hash] data The raw data of the request @since [0.1.1]
[ "Download", "an", "attachment", "from", "a", "message" ]
2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2
https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/api.rb#L305-L309
911
ssut/telegram-rb
lib/telegram/events.rb
Telegram.Event.format_message
def format_message message = Message.new message.id = @id message.text = @raw_data['text'] ||= '' media = @raw_data['media'] message.type = media ? media['type'] : 'text' message.raw_from = @raw_data['from']['peer_id'] message.from_type = @raw_data['from']['peer_type'] message.raw_to = @raw_data['to']['peer_id'] message.to_type = @raw_data['to']['peer_type'] from = @client.contacts.find { |c| c.id == message.raw_from } to = @client.contacts.find { |c| c.id == message.raw_to } to = @client.chats.find { |c| c.id == message.raw_to } if to.nil? message.from = from message.to = to @message = message if @message.from.nil? user = @raw_data['from'] user = TelegramContact.pick_or_new(@client, user) @client.contacts << user unless @client.contacts.include?(user) @message.from = user end if @message.to.nil? type = @raw_data['to']['peer_type'] case type when 'chat', 'encr_chat' chat = TelegramChat.pick_or_new(@client, @raw_data['to']) @client.chats << chat unless @client.chats.include?(chat) if type == 'encr_chat' then @message.to = chat else @message.from = chat end when 'user' user = TelegramContact.pick_or_new(@client, @raw_data['to']) @client.contacts << user unless @client.contacts.include?(user) @message.to = user end end end
ruby
def format_message message = Message.new message.id = @id message.text = @raw_data['text'] ||= '' media = @raw_data['media'] message.type = media ? media['type'] : 'text' message.raw_from = @raw_data['from']['peer_id'] message.from_type = @raw_data['from']['peer_type'] message.raw_to = @raw_data['to']['peer_id'] message.to_type = @raw_data['to']['peer_type'] from = @client.contacts.find { |c| c.id == message.raw_from } to = @client.contacts.find { |c| c.id == message.raw_to } to = @client.chats.find { |c| c.id == message.raw_to } if to.nil? message.from = from message.to = to @message = message if @message.from.nil? user = @raw_data['from'] user = TelegramContact.pick_or_new(@client, user) @client.contacts << user unless @client.contacts.include?(user) @message.from = user end if @message.to.nil? type = @raw_data['to']['peer_type'] case type when 'chat', 'encr_chat' chat = TelegramChat.pick_or_new(@client, @raw_data['to']) @client.chats << chat unless @client.chats.include?(chat) if type == 'encr_chat' then @message.to = chat else @message.from = chat end when 'user' user = TelegramContact.pick_or_new(@client, @raw_data['to']) @client.contacts << user unless @client.contacts.include?(user) @message.to = user end end end
[ "def", "format_message", "message", "=", "Message", ".", "new", "message", ".", "id", "=", "@id", "message", ".", "text", "=", "@raw_data", "[", "'text'", "]", "||=", "''", "media", "=", "@raw_data", "[", "'media'", "]", "message", ".", "type", "=", "media", "?", "media", "[", "'type'", "]", ":", "'text'", "message", ".", "raw_from", "=", "@raw_data", "[", "'from'", "]", "[", "'peer_id'", "]", "message", ".", "from_type", "=", "@raw_data", "[", "'from'", "]", "[", "'peer_type'", "]", "message", ".", "raw_to", "=", "@raw_data", "[", "'to'", "]", "[", "'peer_id'", "]", "message", ".", "to_type", "=", "@raw_data", "[", "'to'", "]", "[", "'peer_type'", "]", "from", "=", "@client", ".", "contacts", ".", "find", "{", "|", "c", "|", "c", ".", "id", "==", "message", ".", "raw_from", "}", "to", "=", "@client", ".", "contacts", ".", "find", "{", "|", "c", "|", "c", ".", "id", "==", "message", ".", "raw_to", "}", "to", "=", "@client", ".", "chats", ".", "find", "{", "|", "c", "|", "c", ".", "id", "==", "message", ".", "raw_to", "}", "if", "to", ".", "nil?", "message", ".", "from", "=", "from", "message", ".", "to", "=", "to", "@message", "=", "message", "if", "@message", ".", "from", ".", "nil?", "user", "=", "@raw_data", "[", "'from'", "]", "user", "=", "TelegramContact", ".", "pick_or_new", "(", "@client", ",", "user", ")", "@client", ".", "contacts", "<<", "user", "unless", "@client", ".", "contacts", ".", "include?", "(", "user", ")", "@message", ".", "from", "=", "user", "end", "if", "@message", ".", "to", ".", "nil?", "type", "=", "@raw_data", "[", "'to'", "]", "[", "'peer_type'", "]", "case", "type", "when", "'chat'", ",", "'encr_chat'", "chat", "=", "TelegramChat", ".", "pick_or_new", "(", "@client", ",", "@raw_data", "[", "'to'", "]", ")", "@client", ".", "chats", "<<", "chat", "unless", "@client", ".", "chats", ".", "include?", "(", "chat", ")", "if", "type", "==", "'encr_chat'", "then", "@message", ".", "to", "=", "chat", "else", "@message", ".", "from", "=", "chat", "end", "when", "'user'", "user", "=", "TelegramContact", ".", "pick_or_new", "(", "@client", ",", "@raw_data", "[", "'to'", "]", ")", "@client", ".", "contacts", "<<", "user", "unless", "@client", ".", "contacts", ".", "include?", "(", "user", ")", "@message", ".", "to", "=", "user", "end", "end", "end" ]
Process raw data in which event type is message given. @return [void] @api private
[ "Process", "raw", "data", "in", "which", "event", "type", "is", "message", "given", "." ]
2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2
https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/events.rb#L161-L206
912
ssut/telegram-rb
lib/telegram/connection.rb
Telegram.Connection.communicate
def communicate(*messages, &callback) @available = false @data = '' @callback = callback messages = messages.first if messages.size == 1 and messages.first.is_a?(Array) messages = messages.join(' ') << "\n" send_data(messages) end
ruby
def communicate(*messages, &callback) @available = false @data = '' @callback = callback messages = messages.first if messages.size == 1 and messages.first.is_a?(Array) messages = messages.join(' ') << "\n" send_data(messages) end
[ "def", "communicate", "(", "*", "messages", ",", "&", "callback", ")", "@available", "=", "false", "@data", "=", "''", "@callback", "=", "callback", "messages", "=", "messages", ".", "first", "if", "messages", ".", "size", "==", "1", "and", "messages", ".", "first", ".", "is_a?", "(", "Array", ")", "messages", "=", "messages", ".", "join", "(", "' '", ")", "<<", "\"\\n\"", "send_data", "(", "messages", ")", "end" ]
Communicate telegram-rb with telegram-cli connection @param [Array<String>] messages Messages that will be sent @yieldparam [Block] callback Callback block that will be called when finished
[ "Communicate", "telegram", "-", "rb", "with", "telegram", "-", "cli", "connection" ]
2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2
https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/connection.rb#L31-L38
913
ssut/telegram-rb
lib/telegram/connection.rb
Telegram.Connection.receive_data
def receive_data(data) @data << data return unless data.index("\n\n") begin result = _receive_data(@data) rescue raise result = nil end @callback.call(!result.nil?, result) unless @callback.nil? @callback = nil @available = true end
ruby
def receive_data(data) @data << data return unless data.index("\n\n") begin result = _receive_data(@data) rescue raise result = nil end @callback.call(!result.nil?, result) unless @callback.nil? @callback = nil @available = true end
[ "def", "receive_data", "(", "data", ")", "@data", "<<", "data", "return", "unless", "data", ".", "index", "(", "\"\\n\\n\"", ")", "begin", "result", "=", "_receive_data", "(", "@data", ")", "rescue", "raise", "result", "=", "nil", "end", "@callback", ".", "call", "(", "!", "result", ".", "nil?", ",", "result", ")", "unless", "@callback", ".", "nil?", "@callback", "=", "nil", "@available", "=", "true", "end" ]
This method will be called by EventMachine when data arrived then parse given data and execute callback method if exists @api private
[ "This", "method", "will", "be", "called", "by", "EventMachine", "when", "data", "arrived", "then", "parse", "given", "data", "and", "execute", "callback", "method", "if", "exists" ]
2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2
https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/connection.rb#L80-L93
914
ssut/telegram-rb
lib/telegram/connection_pool.rb
Telegram.ConnectionPool.acquire
def acquire(&callback) acq = Proc.new { conn = self.find { |conn| conn.available? } if not conn.nil? and conn.connected? callback.call(conn) else logger.warn("Failed to acquire available connection, retry after 0.1 second") EM.add_timer(0.1, &acq) end } EM.add_timer(0, &acq) end
ruby
def acquire(&callback) acq = Proc.new { conn = self.find { |conn| conn.available? } if not conn.nil? and conn.connected? callback.call(conn) else logger.warn("Failed to acquire available connection, retry after 0.1 second") EM.add_timer(0.1, &acq) end } EM.add_timer(0, &acq) end
[ "def", "acquire", "(", "&", "callback", ")", "acq", "=", "Proc", ".", "new", "{", "conn", "=", "self", ".", "find", "{", "|", "conn", "|", "conn", ".", "available?", "}", "if", "not", "conn", ".", "nil?", "and", "conn", ".", "connected?", "callback", ".", "call", "(", "conn", ")", "else", "logger", ".", "warn", "(", "\"Failed to acquire available connection, retry after 0.1 second\"", ")", "EM", ".", "add_timer", "(", "0.1", ",", "acq", ")", "end", "}", "EM", ".", "add_timer", "(", "0", ",", "acq", ")", "end" ]
Acquire available connection @see Connection @param [Block] callback This block will be called when successfully acquired a connection @yieldparam [Connection] connection acquired connection
[ "Acquire", "available", "connection" ]
2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2
https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/connection_pool.rb#L43-L54
915
ssut/telegram-rb
lib/telegram/client.rb
Telegram.Client.execute
def execute cli_arguments = Telegram::CLIArguments.new(@config) command = "'#{@config.daemon}' #{cli_arguments.to_s}" @stdout = IO.popen(command, 'a+') initialize_stdout_reading end
ruby
def execute cli_arguments = Telegram::CLIArguments.new(@config) command = "'#{@config.daemon}' #{cli_arguments.to_s}" @stdout = IO.popen(command, 'a+') initialize_stdout_reading end
[ "def", "execute", "cli_arguments", "=", "Telegram", "::", "CLIArguments", ".", "new", "(", "@config", ")", "command", "=", "\"'#{@config.daemon}' #{cli_arguments.to_s}\"", "@stdout", "=", "IO", ".", "popen", "(", "command", ",", "'a+'", ")", "initialize_stdout_reading", "end" ]
Initialize Telegram Client @yieldparam [Block] block @yield [config] Given configuration struct to the block Execute telegram-cli daemon and wait for the response @api private
[ "Initialize", "Telegram", "Client" ]
2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2
https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/client.rb#L82-L87
916
ssut/telegram-rb
lib/telegram/client.rb
Telegram.Client.poll
def poll logger.info("Start polling for events") while (data = @stdout.gets) begin brace = data.index('{') data = data[brace..-2] data = Oj.load(data, mode: :compat) @events << data rescue end end end
ruby
def poll logger.info("Start polling for events") while (data = @stdout.gets) begin brace = data.index('{') data = data[brace..-2] data = Oj.load(data, mode: :compat) @events << data rescue end end end
[ "def", "poll", "logger", ".", "info", "(", "\"Start polling for events\"", ")", "while", "(", "data", "=", "@stdout", ".", "gets", ")", "begin", "brace", "=", "data", ".", "index", "(", "'{'", ")", "data", "=", "data", "[", "brace", "..", "-", "2", "]", "data", "=", "Oj", ".", "load", "(", "data", ",", "mode", ":", ":compat", ")", "@events", "<<", "data", "rescue", "end", "end", "end" ]
Do the long-polling from stdout of the telegram-cli @api private
[ "Do", "the", "long", "-", "polling", "from", "stdout", "of", "the", "telegram", "-", "cli" ]
2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2
https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/client.rb#L92-L103
917
ssut/telegram-rb
lib/telegram/client.rb
Telegram.Client.connect
def connect(&block) logger.info("Trying to start telegram-cli and then connect") @connect_callback = block process_data EM.defer(method(:execute), method(:create_pool), method(:execution_failed)) end
ruby
def connect(&block) logger.info("Trying to start telegram-cli and then connect") @connect_callback = block process_data EM.defer(method(:execute), method(:create_pool), method(:execution_failed)) end
[ "def", "connect", "(", "&", "block", ")", "logger", ".", "info", "(", "\"Trying to start telegram-cli and then connect\"", ")", "@connect_callback", "=", "block", "process_data", "EM", ".", "defer", "(", "method", "(", ":execute", ")", ",", "method", "(", ":create_pool", ")", ",", "method", "(", ":execution_failed", ")", ")", "end" ]
Start telegram-cli daemon @yield This block will be executed when all connections have responded
[ "Start", "telegram", "-", "cli", "daemon" ]
2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2
https://github.com/ssut/telegram-rb/blob/2c6b1843a0c9c4e8d5cade18f014ee1e34d4ebd2/lib/telegram/client.rb#L144-L149
918
bpot/poseidon
lib/poseidon/message_set.rb
Poseidon.MessageSet.flatten
def flatten messages = struct.messages.map do |message| if message.compressed? s = message.decompressed_value MessageSet.read_without_size(Protocol::ResponseBuffer.new(s)).flatten else message end end.flatten end
ruby
def flatten messages = struct.messages.map do |message| if message.compressed? s = message.decompressed_value MessageSet.read_without_size(Protocol::ResponseBuffer.new(s)).flatten else message end end.flatten end
[ "def", "flatten", "messages", "=", "struct", ".", "messages", ".", "map", "do", "|", "message", "|", "if", "message", ".", "compressed?", "s", "=", "message", ".", "decompressed_value", "MessageSet", ".", "read_without_size", "(", "Protocol", "::", "ResponseBuffer", ".", "new", "(", "s", ")", ")", ".", "flatten", "else", "message", "end", "end", ".", "flatten", "end" ]
Builds an array of Message objects from the MessageStruct objects. Decompressing messages if necessary. @return [Array<Message>]
[ "Builds", "an", "array", "of", "Message", "objects", "from", "the", "MessageStruct", "objects", ".", "Decompressing", "messages", "if", "necessary", "." ]
bfbf084ea21af2a31350ad5f58d8ef5dc30b948e
https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/message_set.rb#L59-L68
919
bpot/poseidon
lib/poseidon/messages_for_broker.rb
Poseidon.MessagesForBroker.add
def add(message, partition_id) @messages << message @topics[message.topic] ||= {} @topics[message.topic][partition_id] ||= [] @topics[message.topic][partition_id] << message end
ruby
def add(message, partition_id) @messages << message @topics[message.topic] ||= {} @topics[message.topic][partition_id] ||= [] @topics[message.topic][partition_id] << message end
[ "def", "add", "(", "message", ",", "partition_id", ")", "@messages", "<<", "message", "@topics", "[", "message", ".", "topic", "]", "||=", "{", "}", "@topics", "[", "message", ".", "topic", "]", "[", "partition_id", "]", "||=", "[", "]", "@topics", "[", "message", ".", "topic", "]", "[", "partition_id", "]", "<<", "message", "end" ]
Add a messages for this broker
[ "Add", "a", "messages", "for", "this", "broker" ]
bfbf084ea21af2a31350ad5f58d8ef5dc30b948e
https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/messages_for_broker.rb#L14-L20
920
bpot/poseidon
lib/poseidon/messages_for_broker.rb
Poseidon.MessagesForBroker.build_protocol_objects
def build_protocol_objects(compression_config) @topics.map do |topic, messages_by_partition| codec = compression_config.compression_codec_for_topic(topic) messages_for_partitions = messages_by_partition.map do |partition, messages| message_set = MessageSet.new(messages) if codec Protocol::MessagesForPartition.new(partition, message_set.compress(codec)) else Protocol::MessagesForPartition.new(partition, message_set) end end Protocol::MessagesForTopic.new(topic, messages_for_partitions) end end
ruby
def build_protocol_objects(compression_config) @topics.map do |topic, messages_by_partition| codec = compression_config.compression_codec_for_topic(topic) messages_for_partitions = messages_by_partition.map do |partition, messages| message_set = MessageSet.new(messages) if codec Protocol::MessagesForPartition.new(partition, message_set.compress(codec)) else Protocol::MessagesForPartition.new(partition, message_set) end end Protocol::MessagesForTopic.new(topic, messages_for_partitions) end end
[ "def", "build_protocol_objects", "(", "compression_config", ")", "@topics", ".", "map", "do", "|", "topic", ",", "messages_by_partition", "|", "codec", "=", "compression_config", ".", "compression_codec_for_topic", "(", "topic", ")", "messages_for_partitions", "=", "messages_by_partition", ".", "map", "do", "|", "partition", ",", "messages", "|", "message_set", "=", "MessageSet", ".", "new", "(", "messages", ")", "if", "codec", "Protocol", "::", "MessagesForPartition", ".", "new", "(", "partition", ",", "message_set", ".", "compress", "(", "codec", ")", ")", "else", "Protocol", "::", "MessagesForPartition", ".", "new", "(", "partition", ",", "message_set", ")", "end", "end", "Protocol", "::", "MessagesForTopic", ".", "new", "(", "topic", ",", "messages_for_partitions", ")", "end", "end" ]
Build protocol objects for this broker!
[ "Build", "protocol", "objects", "for", "this", "broker!" ]
bfbf084ea21af2a31350ad5f58d8ef5dc30b948e
https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/messages_for_broker.rb#L23-L37
921
bpot/poseidon
lib/poseidon/messages_to_send_batch.rb
Poseidon.MessagesToSendBatch.messages_for_brokers
def messages_for_brokers messages_for_broker_ids = {} @messages.each do |message| partition_id, broker_id = @message_conductor.destination(message.topic, message.key) # Create a nested hash to group messages by broker_id, topic, partition. messages_for_broker_ids[broker_id] ||= MessagesForBroker.new(broker_id) messages_for_broker_ids[broker_id].add(message, partition_id) end messages_for_broker_ids.values end
ruby
def messages_for_brokers messages_for_broker_ids = {} @messages.each do |message| partition_id, broker_id = @message_conductor.destination(message.topic, message.key) # Create a nested hash to group messages by broker_id, topic, partition. messages_for_broker_ids[broker_id] ||= MessagesForBroker.new(broker_id) messages_for_broker_ids[broker_id].add(message, partition_id) end messages_for_broker_ids.values end
[ "def", "messages_for_brokers", "messages_for_broker_ids", "=", "{", "}", "@messages", ".", "each", "do", "|", "message", "|", "partition_id", ",", "broker_id", "=", "@message_conductor", ".", "destination", "(", "message", ".", "topic", ",", "message", ".", "key", ")", "# Create a nested hash to group messages by broker_id, topic, partition.", "messages_for_broker_ids", "[", "broker_id", "]", "||=", "MessagesForBroker", ".", "new", "(", "broker_id", ")", "messages_for_broker_ids", "[", "broker_id", "]", ".", "add", "(", "message", ",", "partition_id", ")", "end", "messages_for_broker_ids", ".", "values", "end" ]
Groups messages by broker and preps them for transmission. @return [Array<MessagesForBroker>]
[ "Groups", "messages", "by", "broker", "and", "preps", "them", "for", "transmission", "." ]
bfbf084ea21af2a31350ad5f58d8ef5dc30b948e
https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/messages_to_send_batch.rb#L13-L25
922
bpot/poseidon
lib/poseidon/connection.rb
Poseidon.Connection.produce
def produce(required_acks, timeout, messages_for_topics) ensure_connected req = ProduceRequest.new( request_common(:produce), required_acks, timeout, messages_for_topics) send_request(req) if required_acks != 0 read_response(ProduceResponse) else true end end
ruby
def produce(required_acks, timeout, messages_for_topics) ensure_connected req = ProduceRequest.new( request_common(:produce), required_acks, timeout, messages_for_topics) send_request(req) if required_acks != 0 read_response(ProduceResponse) else true end end
[ "def", "produce", "(", "required_acks", ",", "timeout", ",", "messages_for_topics", ")", "ensure_connected", "req", "=", "ProduceRequest", ".", "new", "(", "request_common", "(", ":produce", ")", ",", "required_acks", ",", "timeout", ",", "messages_for_topics", ")", "send_request", "(", "req", ")", "if", "required_acks", "!=", "0", "read_response", "(", "ProduceResponse", ")", "else", "true", "end", "end" ]
Execute a produce call @param [Integer] required_acks @param [Integer] timeout @param [Array<Protocol::MessagesForTopics>] messages_for_topics Messages to send @return [ProduceResponse]
[ "Execute", "a", "produce", "call" ]
bfbf084ea21af2a31350ad5f58d8ef5dc30b948e
https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/connection.rb#L49-L61
923
bpot/poseidon
lib/poseidon/connection.rb
Poseidon.Connection.fetch
def fetch(max_wait_time, min_bytes, topic_fetches) ensure_connected req = FetchRequest.new( request_common(:fetch), REPLICA_ID, max_wait_time, min_bytes, topic_fetches) send_request(req) read_response(FetchResponse) end
ruby
def fetch(max_wait_time, min_bytes, topic_fetches) ensure_connected req = FetchRequest.new( request_common(:fetch), REPLICA_ID, max_wait_time, min_bytes, topic_fetches) send_request(req) read_response(FetchResponse) end
[ "def", "fetch", "(", "max_wait_time", ",", "min_bytes", ",", "topic_fetches", ")", "ensure_connected", "req", "=", "FetchRequest", ".", "new", "(", "request_common", "(", ":fetch", ")", ",", "REPLICA_ID", ",", "max_wait_time", ",", "min_bytes", ",", "topic_fetches", ")", "send_request", "(", "req", ")", "read_response", "(", "FetchResponse", ")", "end" ]
Execute a fetch call @param [Integer] max_wait_time @param [Integer] min_bytes @param [Integer] topic_fetches
[ "Execute", "a", "fetch", "call" ]
bfbf084ea21af2a31350ad5f58d8ef5dc30b948e
https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/connection.rb#L68-L77
924
bpot/poseidon
lib/poseidon/connection.rb
Poseidon.Connection.topic_metadata
def topic_metadata(topic_names) ensure_connected req = MetadataRequest.new( request_common(:metadata), topic_names) send_request(req) read_response(MetadataResponse) end
ruby
def topic_metadata(topic_names) ensure_connected req = MetadataRequest.new( request_common(:metadata), topic_names) send_request(req) read_response(MetadataResponse) end
[ "def", "topic_metadata", "(", "topic_names", ")", "ensure_connected", "req", "=", "MetadataRequest", ".", "new", "(", "request_common", "(", ":metadata", ")", ",", "topic_names", ")", "send_request", "(", "req", ")", "read_response", "(", "MetadataResponse", ")", "end" ]
Fetch metadata for +topic_names+ @param [Enumberable<String>] topic_names A list of topics to retrive metadata for @return [TopicMetadataResponse] metadata for the topics
[ "Fetch", "metadata", "for", "+", "topic_names", "+" ]
bfbf084ea21af2a31350ad5f58d8ef5dc30b948e
https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/connection.rb#L93-L99
925
bpot/poseidon
lib/poseidon/cluster_metadata.rb
Poseidon.ClusterMetadata.update
def update(topic_metadata_response) update_brokers(topic_metadata_response.brokers) update_topics(topic_metadata_response.topics) @last_refreshed_at = Time.now nil end
ruby
def update(topic_metadata_response) update_brokers(topic_metadata_response.brokers) update_topics(topic_metadata_response.topics) @last_refreshed_at = Time.now nil end
[ "def", "update", "(", "topic_metadata_response", ")", "update_brokers", "(", "topic_metadata_response", ".", "brokers", ")", "update_topics", "(", "topic_metadata_response", ".", "topics", ")", "@last_refreshed_at", "=", "Time", ".", "now", "nil", "end" ]
Update what we know about the cluter based on MetadataResponse @param [MetadataResponse] topic_metadata_response @return nil
[ "Update", "what", "we", "know", "about", "the", "cluter", "based", "on", "MetadataResponse" ]
bfbf084ea21af2a31350ad5f58d8ef5dc30b948e
https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/cluster_metadata.rb#L18-L24
926
bpot/poseidon
lib/poseidon/message_conductor.rb
Poseidon.MessageConductor.destination
def destination(topic, key = nil) topic_metadata = topic_metadatas[topic] if topic_metadata && topic_metadata.leader_available? partition_id = determine_partition(topic_metadata, key) broker_id = topic_metadata.partition_leader(partition_id) || NO_BROKER else partition_id = NO_PARTITION broker_id = NO_BROKER end return partition_id, broker_id end
ruby
def destination(topic, key = nil) topic_metadata = topic_metadatas[topic] if topic_metadata && topic_metadata.leader_available? partition_id = determine_partition(topic_metadata, key) broker_id = topic_metadata.partition_leader(partition_id) || NO_BROKER else partition_id = NO_PARTITION broker_id = NO_BROKER end return partition_id, broker_id end
[ "def", "destination", "(", "topic", ",", "key", "=", "nil", ")", "topic_metadata", "=", "topic_metadatas", "[", "topic", "]", "if", "topic_metadata", "&&", "topic_metadata", ".", "leader_available?", "partition_id", "=", "determine_partition", "(", "topic_metadata", ",", "key", ")", "broker_id", "=", "topic_metadata", ".", "partition_leader", "(", "partition_id", ")", "||", "NO_BROKER", "else", "partition_id", "=", "NO_PARTITION", "broker_id", "=", "NO_BROKER", "end", "return", "partition_id", ",", "broker_id", "end" ]
Create a new message conductor @param [Hash<String,TopicMetadata>] topics_metadata Metadata for all topics this conductor may receive. @param [Object] partitioner Custom partitioner Determines which partition a message should be sent to. @param [String] topic Topic we are sending this message to @param [Object] key Key for this message, may be nil @return [Integer,Integer] partition_id and broker_id to which this message should be sent
[ "Create", "a", "new", "message", "conductor" ]
bfbf084ea21af2a31350ad5f58d8ef5dc30b948e
https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/message_conductor.rb#L30-L41
927
bpot/poseidon
lib/poseidon/partition_consumer.rb
Poseidon.PartitionConsumer.fetch
def fetch(options = {}) fetch_max_wait = options.delete(:max_wait_ms) || max_wait_ms fetch_max_bytes = options.delete(:max_bytes) || max_bytes fetch_min_bytes = options.delete(:min_bytes) || min_bytes if options.keys.any? raise ArgumentError, "Unknown options: #{options.keys.inspect}" end topic_fetches = build_topic_fetch_request(fetch_max_bytes) fetch_response = @connection.fetch(fetch_max_wait, fetch_min_bytes, topic_fetches) topic_response = fetch_response.topic_fetch_responses.first partition_response = topic_response.partition_fetch_responses.first unless partition_response.error == Errors::NO_ERROR_CODE if @offset < 0 && Errors::ERROR_CODES[partition_response.error] == Errors::OffsetOutOfRange @offset = :earliest_offset return fetch(options) end raise Errors::ERROR_CODES[partition_response.error] else @highwater_mark = partition_response.highwater_mark_offset messages = partition_response.message_set.flatten.map do |m| FetchedMessage.new(topic_response.topic, m.value, m.key, m.offset) end if messages.any? @offset = messages.last.offset + 1 end messages end end
ruby
def fetch(options = {}) fetch_max_wait = options.delete(:max_wait_ms) || max_wait_ms fetch_max_bytes = options.delete(:max_bytes) || max_bytes fetch_min_bytes = options.delete(:min_bytes) || min_bytes if options.keys.any? raise ArgumentError, "Unknown options: #{options.keys.inspect}" end topic_fetches = build_topic_fetch_request(fetch_max_bytes) fetch_response = @connection.fetch(fetch_max_wait, fetch_min_bytes, topic_fetches) topic_response = fetch_response.topic_fetch_responses.first partition_response = topic_response.partition_fetch_responses.first unless partition_response.error == Errors::NO_ERROR_CODE if @offset < 0 && Errors::ERROR_CODES[partition_response.error] == Errors::OffsetOutOfRange @offset = :earliest_offset return fetch(options) end raise Errors::ERROR_CODES[partition_response.error] else @highwater_mark = partition_response.highwater_mark_offset messages = partition_response.message_set.flatten.map do |m| FetchedMessage.new(topic_response.topic, m.value, m.key, m.offset) end if messages.any? @offset = messages.last.offset + 1 end messages end end
[ "def", "fetch", "(", "options", "=", "{", "}", ")", "fetch_max_wait", "=", "options", ".", "delete", "(", ":max_wait_ms", ")", "||", "max_wait_ms", "fetch_max_bytes", "=", "options", ".", "delete", "(", ":max_bytes", ")", "||", "max_bytes", "fetch_min_bytes", "=", "options", ".", "delete", "(", ":min_bytes", ")", "||", "min_bytes", "if", "options", ".", "keys", ".", "any?", "raise", "ArgumentError", ",", "\"Unknown options: #{options.keys.inspect}\"", "end", "topic_fetches", "=", "build_topic_fetch_request", "(", "fetch_max_bytes", ")", "fetch_response", "=", "@connection", ".", "fetch", "(", "fetch_max_wait", ",", "fetch_min_bytes", ",", "topic_fetches", ")", "topic_response", "=", "fetch_response", ".", "topic_fetch_responses", ".", "first", "partition_response", "=", "topic_response", ".", "partition_fetch_responses", ".", "first", "unless", "partition_response", ".", "error", "==", "Errors", "::", "NO_ERROR_CODE", "if", "@offset", "<", "0", "&&", "Errors", "::", "ERROR_CODES", "[", "partition_response", ".", "error", "]", "==", "Errors", "::", "OffsetOutOfRange", "@offset", "=", ":earliest_offset", "return", "fetch", "(", "options", ")", "end", "raise", "Errors", "::", "ERROR_CODES", "[", "partition_response", ".", "error", "]", "else", "@highwater_mark", "=", "partition_response", ".", "highwater_mark_offset", "messages", "=", "partition_response", ".", "message_set", ".", "flatten", ".", "map", "do", "|", "m", "|", "FetchedMessage", ".", "new", "(", "topic_response", ".", "topic", ",", "m", ".", "value", ",", "m", ".", "key", ",", "m", ".", "offset", ")", "end", "if", "messages", ".", "any?", "@offset", "=", "messages", ".", "last", ".", "offset", "+", "1", "end", "messages", "end", "end" ]
Create a new consumer which reads the specified topic and partition from the host. @param [String] client_id Used to identify this client should be unique. @param [String] host @param [Integer] port @param [String] topic Topic to read from @param [Integer] partition Partitions are zero indexed. @param [Integer,Symbol] offset Offset to start reading from. A negative offset can also be passed. There are a couple special offsets which can be passed as symbols: :earliest_offset Start reading from the first offset the server has. :latest_offset Start reading from the latest offset the server has. @param [Hash] options Theses options can all be overridden in each individual fetch command. @option options [Integer] :max_bytes Maximum number of bytes to fetch Default: 1048576 (1MB) @option options [Integer] :max_wait_ms How long to block until the server sends us data. NOTE: This is only enforced if min_bytes is > 0. Default: 100 (100ms) @option options [Integer] :min_bytes Smallest amount of data the server should send us. Default: 1 (Send us data as soon as it is ready) @option options [Integer] :socket_timeout_ms How long to wait for reply from server. Should be higher than max_wait_ms. Default: 10000 (10s) @api public Fetch messages from the broker. @param [Hash] options @option options [Integer] :max_bytes Maximum number of bytes to fetch @option options [Integer] :max_wait_ms How long to block until the server sends us data. @option options [Integer] :min_bytes Smallest amount of data the server should send us. @api public
[ "Create", "a", "new", "consumer", "which", "reads", "the", "specified", "topic", "and", "partition", "from", "the", "host", "." ]
bfbf084ea21af2a31350ad5f58d8ef5dc30b948e
https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/partition_consumer.rb#L100-L132
928
bpot/poseidon
lib/poseidon/producer.rb
Poseidon.Producer.send_messages
def send_messages(messages) raise Errors::ProducerShutdownError if @shutdown if !messages.respond_to?(:each) raise ArgumentError, "messages must respond to #each" end @producer.send_messages(convert_to_messages_objects(messages)) end
ruby
def send_messages(messages) raise Errors::ProducerShutdownError if @shutdown if !messages.respond_to?(:each) raise ArgumentError, "messages must respond to #each" end @producer.send_messages(convert_to_messages_objects(messages)) end
[ "def", "send_messages", "(", "messages", ")", "raise", "Errors", "::", "ProducerShutdownError", "if", "@shutdown", "if", "!", "messages", ".", "respond_to?", "(", ":each", ")", "raise", "ArgumentError", ",", "\"messages must respond to #each\"", "end", "@producer", ".", "send_messages", "(", "convert_to_messages_objects", "(", "messages", ")", ")", "end" ]
Returns a new Producer. @param [Array<String>] brokers An array of brokers in the form "host1:port1" @param [String] client_id A client_id used to indentify the producer. @param [Hash] options @option options [:sync / :async] :type (:sync) Whether we should send messages right away or queue them and send them in the background. @option options [:gzip / :snappy / :none] :compression_codec (:none) Type of compression to use. @option options [Enumberable<String>] :compressed_topics (nil) Topics to compress. If this is not specified we will compress all topics provided that +:compression_codec+ is set. @option options [Integer: Milliseconds] :metadata_refresh_interval_ms (600_000) How frequently we should update the topic metadata in milliseconds. @option options [#call, nil] :partitioner Object which partitions messages based on key. Responds to #call(key, partition_count). @option options [Integer] :max_send_retries (3) Number of times to retry sending of messages to a leader. @option options [Integer] :retry_backoff_ms (100) The amount of time (in milliseconds) to wait before refreshing the metadata after we are unable to send messages. Number of times to retry sending of messages to a leader. @option options [Integer] :required_acks (0) The number of acks required per request. @option options [Integer] :ack_timeout_ms (1500) How long the producer waits for acks. @option options [Integer] :socket_timeout_ms] (10000) How long the producer socket waits for any reply from server. @api public Send messages to the cluster. Raises an exception if the producer fails to send the messages. @param [Enumerable<MessageToSend>] messages Messages must have a +topic+ set and may have a +key+ set. @return [Boolean] @api public
[ "Returns", "a", "new", "Producer", "." ]
bfbf084ea21af2a31350ad5f58d8ef5dc30b948e
https://github.com/bpot/poseidon/blob/bfbf084ea21af2a31350ad5f58d8ef5dc30b948e/lib/poseidon/producer.rb#L157-L164
929
piotrmurach/tty-screen
lib/tty/screen.rb
TTY.Screen.size
def size size = size_from_java size ||= size_from_win_api size ||= size_from_ioctl size ||= size_from_io_console size ||= size_from_readline size ||= size_from_tput size ||= size_from_stty size ||= size_from_env size ||= size_from_ansicon size || DEFAULT_SIZE end
ruby
def size size = size_from_java size ||= size_from_win_api size ||= size_from_ioctl size ||= size_from_io_console size ||= size_from_readline size ||= size_from_tput size ||= size_from_stty size ||= size_from_env size ||= size_from_ansicon size || DEFAULT_SIZE end
[ "def", "size", "size", "=", "size_from_java", "size", "||=", "size_from_win_api", "size", "||=", "size_from_ioctl", "size", "||=", "size_from_io_console", "size", "||=", "size_from_readline", "size", "||=", "size_from_tput", "size", "||=", "size_from_stty", "size", "||=", "size_from_env", "size", "||=", "size_from_ansicon", "size", "||", "DEFAULT_SIZE", "end" ]
Get terminal rows and columns @return [Array[Integer, Integer]] return rows & columns @api public
[ "Get", "terminal", "rows", "and", "columns" ]
282ae528974059c16090212dbcfb4a3d5aa3bbeb
https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L39-L50
930
piotrmurach/tty-screen
lib/tty/screen.rb
TTY.Screen.size_from_win_api
def size_from_win_api(verbose: nil) require 'fiddle' kernel32 = Fiddle::Handle.new('kernel32') get_std_handle = Fiddle::Function.new(kernel32['GetStdHandle'], [-Fiddle::TYPE_INT], Fiddle::TYPE_INT) get_console_buffer_info = Fiddle::Function.new( kernel32['GetConsoleScreenBufferInfo'], [Fiddle::TYPE_LONG, Fiddle::TYPE_VOIDP], Fiddle::TYPE_INT) format = 'SSSSSssssSS' buffer = ([0] * format.size).pack(format) stdout_handle = get_std_handle.(STDOUT_HANDLE) get_console_buffer_info.(stdout_handle, buffer) _, _, _, _, _, left, top, right, bottom, = buffer.unpack(format) size = [bottom - top + 1, right - left + 1] return size if nonzero_column?(size[1] - 1) rescue LoadError warn 'no native fiddle module found' if verbose rescue Fiddle::DLError # non windows platform or no kernel32 lib end
ruby
def size_from_win_api(verbose: nil) require 'fiddle' kernel32 = Fiddle::Handle.new('kernel32') get_std_handle = Fiddle::Function.new(kernel32['GetStdHandle'], [-Fiddle::TYPE_INT], Fiddle::TYPE_INT) get_console_buffer_info = Fiddle::Function.new( kernel32['GetConsoleScreenBufferInfo'], [Fiddle::TYPE_LONG, Fiddle::TYPE_VOIDP], Fiddle::TYPE_INT) format = 'SSSSSssssSS' buffer = ([0] * format.size).pack(format) stdout_handle = get_std_handle.(STDOUT_HANDLE) get_console_buffer_info.(stdout_handle, buffer) _, _, _, _, _, left, top, right, bottom, = buffer.unpack(format) size = [bottom - top + 1, right - left + 1] return size if nonzero_column?(size[1] - 1) rescue LoadError warn 'no native fiddle module found' if verbose rescue Fiddle::DLError # non windows platform or no kernel32 lib end
[ "def", "size_from_win_api", "(", "verbose", ":", "nil", ")", "require", "'fiddle'", "kernel32", "=", "Fiddle", "::", "Handle", ".", "new", "(", "'kernel32'", ")", "get_std_handle", "=", "Fiddle", "::", "Function", ".", "new", "(", "kernel32", "[", "'GetStdHandle'", "]", ",", "[", "-", "Fiddle", "::", "TYPE_INT", "]", ",", "Fiddle", "::", "TYPE_INT", ")", "get_console_buffer_info", "=", "Fiddle", "::", "Function", ".", "new", "(", "kernel32", "[", "'GetConsoleScreenBufferInfo'", "]", ",", "[", "Fiddle", "::", "TYPE_LONG", ",", "Fiddle", "::", "TYPE_VOIDP", "]", ",", "Fiddle", "::", "TYPE_INT", ")", "format", "=", "'SSSSSssssSS'", "buffer", "=", "(", "[", "0", "]", "*", "format", ".", "size", ")", ".", "pack", "(", "format", ")", "stdout_handle", "=", "get_std_handle", ".", "(", "STDOUT_HANDLE", ")", "get_console_buffer_info", ".", "(", "stdout_handle", ",", "buffer", ")", "_", ",", "_", ",", "_", ",", "_", ",", "_", ",", "left", ",", "top", ",", "right", ",", "bottom", ",", "=", "buffer", ".", "unpack", "(", "format", ")", "size", "=", "[", "bottom", "-", "top", "+", "1", ",", "right", "-", "left", "+", "1", "]", "return", "size", "if", "nonzero_column?", "(", "size", "[", "1", "]", "-", "1", ")", "rescue", "LoadError", "warn", "'no native fiddle module found'", "if", "verbose", "rescue", "Fiddle", "::", "DLError", "# non windows platform or no kernel32 lib", "end" ]
Determine terminal size with a Windows native API @return [nil, Array[Integer, Integer]] @api private
[ "Determine", "terminal", "size", "with", "a", "Windows", "native", "API" ]
282ae528974059c16090212dbcfb4a3d5aa3bbeb
https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L80-L102
931
piotrmurach/tty-screen
lib/tty/screen.rb
TTY.Screen.size_from_java
def size_from_java(verbose: nil) return unless jruby? require 'java' java_import 'jline.TerminalFactory' terminal = TerminalFactory.get size = [terminal.get_height, terminal.get_width] return size if nonzero_column?(size[1]) rescue warn 'failed to import java terminal package' if verbose end
ruby
def size_from_java(verbose: nil) return unless jruby? require 'java' java_import 'jline.TerminalFactory' terminal = TerminalFactory.get size = [terminal.get_height, terminal.get_width] return size if nonzero_column?(size[1]) rescue warn 'failed to import java terminal package' if verbose end
[ "def", "size_from_java", "(", "verbose", ":", "nil", ")", "return", "unless", "jruby?", "require", "'java'", "java_import", "'jline.TerminalFactory'", "terminal", "=", "TerminalFactory", ".", "get", "size", "=", "[", "terminal", ".", "get_height", ",", "terminal", ".", "get_width", "]", "return", "size", "if", "nonzero_column?", "(", "size", "[", "1", "]", ")", "rescue", "warn", "'failed to import java terminal package'", "if", "verbose", "end" ]
Determine terminal size on jruby using native Java libs @return [nil, Array[Integer, Integer]] @api private
[ "Determine", "terminal", "size", "on", "jruby", "using", "native", "Java", "libs" ]
282ae528974059c16090212dbcfb4a3d5aa3bbeb
https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L110-L119
932
piotrmurach/tty-screen
lib/tty/screen.rb
TTY.Screen.size_from_ioctl
def size_from_ioctl return if jruby? return unless @output.respond_to?(:ioctl) format = 'SSSS' buffer = ([0] * format.size).pack(format) if ioctl?(TIOCGWINSZ, buffer) || ioctl?(TIOCGWINSZ_PPC, buffer) rows, cols, = buffer.unpack(format)[0..1] return [rows, cols] if nonzero_column?(cols) end end
ruby
def size_from_ioctl return if jruby? return unless @output.respond_to?(:ioctl) format = 'SSSS' buffer = ([0] * format.size).pack(format) if ioctl?(TIOCGWINSZ, buffer) || ioctl?(TIOCGWINSZ_PPC, buffer) rows, cols, = buffer.unpack(format)[0..1] return [rows, cols] if nonzero_column?(cols) end end
[ "def", "size_from_ioctl", "return", "if", "jruby?", "return", "unless", "@output", ".", "respond_to?", "(", ":ioctl", ")", "format", "=", "'SSSS'", "buffer", "=", "(", "[", "0", "]", "*", "format", ".", "size", ")", ".", "pack", "(", "format", ")", "if", "ioctl?", "(", "TIOCGWINSZ", ",", "buffer", ")", "||", "ioctl?", "(", "TIOCGWINSZ_PPC", ",", "buffer", ")", "rows", ",", "cols", ",", "=", "buffer", ".", "unpack", "(", "format", ")", "[", "0", "..", "1", "]", "return", "[", "rows", ",", "cols", "]", "if", "nonzero_column?", "(", "cols", ")", "end", "end" ]
Read terminal size from Unix ioctl @return [nil, Array[Integer, Integer]] @api private
[ "Read", "terminal", "size", "from", "Unix", "ioctl" ]
282ae528974059c16090212dbcfb4a3d5aa3bbeb
https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L156-L166
933
piotrmurach/tty-screen
lib/tty/screen.rb
TTY.Screen.size_from_readline
def size_from_readline if defined?(Readline) && Readline.respond_to?(:get_screen_size) size = Readline.get_screen_size size if nonzero_column?(size[1]) end rescue NotImplementedError end
ruby
def size_from_readline if defined?(Readline) && Readline.respond_to?(:get_screen_size) size = Readline.get_screen_size size if nonzero_column?(size[1]) end rescue NotImplementedError end
[ "def", "size_from_readline", "if", "defined?", "(", "Readline", ")", "&&", "Readline", ".", "respond_to?", "(", ":get_screen_size", ")", "size", "=", "Readline", ".", "get_screen_size", "size", "if", "nonzero_column?", "(", "size", "[", "1", "]", ")", "end", "rescue", "NotImplementedError", "end" ]
Detect screen size using Readline @api private
[ "Detect", "screen", "size", "using", "Readline" ]
282ae528974059c16090212dbcfb4a3d5aa3bbeb
https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L182-L188
934
piotrmurach/tty-screen
lib/tty/screen.rb
TTY.Screen.size_from_tput
def size_from_tput return unless @output.tty? lines = run_command('tput', 'lines').to_i cols = run_command('tput', 'cols').to_i [lines, cols] if nonzero_column?(lines) rescue IOError, SystemCallError end
ruby
def size_from_tput return unless @output.tty? lines = run_command('tput', 'lines').to_i cols = run_command('tput', 'cols').to_i [lines, cols] if nonzero_column?(lines) rescue IOError, SystemCallError end
[ "def", "size_from_tput", "return", "unless", "@output", ".", "tty?", "lines", "=", "run_command", "(", "'tput'", ",", "'lines'", ")", ".", "to_i", "cols", "=", "run_command", "(", "'tput'", ",", "'cols'", ")", ".", "to_i", "[", "lines", ",", "cols", "]", "if", "nonzero_column?", "(", "lines", ")", "rescue", "IOError", ",", "SystemCallError", "end" ]
Detect terminal size from tput utility @api private
[ "Detect", "terminal", "size", "from", "tput", "utility" ]
282ae528974059c16090212dbcfb4a3d5aa3bbeb
https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L194-L200
935
piotrmurach/tty-screen
lib/tty/screen.rb
TTY.Screen.size_from_stty
def size_from_stty return unless @output.tty? out = run_command('stty', 'size') return unless out size = out.split.map(&:to_i) size if nonzero_column?(size[1]) rescue IOError, SystemCallError end
ruby
def size_from_stty return unless @output.tty? out = run_command('stty', 'size') return unless out size = out.split.map(&:to_i) size if nonzero_column?(size[1]) rescue IOError, SystemCallError end
[ "def", "size_from_stty", "return", "unless", "@output", ".", "tty?", "out", "=", "run_command", "(", "'stty'", ",", "'size'", ")", "return", "unless", "out", "size", "=", "out", ".", "split", ".", "map", "(", ":to_i", ")", "size", "if", "nonzero_column?", "(", "size", "[", "1", "]", ")", "rescue", "IOError", ",", "SystemCallError", "end" ]
Detect terminal size from stty utility @api private
[ "Detect", "terminal", "size", "from", "stty", "utility" ]
282ae528974059c16090212dbcfb4a3d5aa3bbeb
https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L206-L213
936
piotrmurach/tty-screen
lib/tty/screen.rb
TTY.Screen.run_command
def run_command(*args) require 'tempfile' out = Tempfile.new('tty-screen') result = system(*args, out: out.path, err: File::NULL) return if result.nil? out.rewind out.read ensure out.close if out end
ruby
def run_command(*args) require 'tempfile' out = Tempfile.new('tty-screen') result = system(*args, out: out.path, err: File::NULL) return if result.nil? out.rewind out.read ensure out.close if out end
[ "def", "run_command", "(", "*", "args", ")", "require", "'tempfile'", "out", "=", "Tempfile", ".", "new", "(", "'tty-screen'", ")", "result", "=", "system", "(", "args", ",", "out", ":", "out", ".", "path", ",", "err", ":", "File", "::", "NULL", ")", "return", "if", "result", ".", "nil?", "out", ".", "rewind", "out", ".", "read", "ensure", "out", ".", "close", "if", "out", "end" ]
Runs command silently capturing the output @api private
[ "Runs", "command", "silently", "capturing", "the", "output" ]
282ae528974059c16090212dbcfb4a3d5aa3bbeb
https://github.com/piotrmurach/tty-screen/blob/282ae528974059c16090212dbcfb4a3d5aa3bbeb/lib/tty/screen.rb#L246-L255
937
jpmckinney/multi_mail
lib/multi_mail/service.rb
MultiMail.Service.validate_options
def validate_options(options, raise_error_if_unrecognized = true) keys = [] for key, value in options unless value.nil? keys << key end end missing = requirements - keys unless missing.empty? raise ArgumentError, "Missing required arguments: #{missing.map(&:to_s).sort.join(', ')}" end if !recognizes.empty? && raise_error_if_unrecognized unrecognized = options.keys - requirements - recognized unless unrecognized.empty? raise ArgumentError, "Unrecognized arguments: #{unrecognized.map(&:to_s).sort.join(', ')}" end end end
ruby
def validate_options(options, raise_error_if_unrecognized = true) keys = [] for key, value in options unless value.nil? keys << key end end missing = requirements - keys unless missing.empty? raise ArgumentError, "Missing required arguments: #{missing.map(&:to_s).sort.join(', ')}" end if !recognizes.empty? && raise_error_if_unrecognized unrecognized = options.keys - requirements - recognized unless unrecognized.empty? raise ArgumentError, "Unrecognized arguments: #{unrecognized.map(&:to_s).sort.join(', ')}" end end end
[ "def", "validate_options", "(", "options", ",", "raise_error_if_unrecognized", "=", "true", ")", "keys", "=", "[", "]", "for", "key", ",", "value", "in", "options", "unless", "value", ".", "nil?", "keys", "<<", "key", "end", "end", "missing", "=", "requirements", "-", "keys", "unless", "missing", ".", "empty?", "raise", "ArgumentError", ",", "\"Missing required arguments: #{missing.map(&:to_s).sort.join(', ')}\"", "end", "if", "!", "recognizes", ".", "empty?", "&&", "raise_error_if_unrecognized", "unrecognized", "=", "options", ".", "keys", "-", "requirements", "-", "recognized", "unless", "unrecognized", ".", "empty?", "raise", "ArgumentError", ",", "\"Unrecognized arguments: #{unrecognized.map(&:to_s).sort.join(', ')}\"", "end", "end", "end" ]
Ensures that required arguments are present and that optional arguments are recognized. @param [Hash] options arguments @raise [ArgumentError] if it can't find a required argument or can't recognize an optional argument @see Fog::Service::validate_options
[ "Ensures", "that", "required", "arguments", "are", "present", "and", "that", "optional", "arguments", "are", "recognized", "." ]
4c9d7310633c1034afbef0dab873e89a8c608d00
https://github.com/jpmckinney/multi_mail/blob/4c9d7310633c1034afbef0dab873e89a8c608d00/lib/multi_mail/service.rb#L45-L64
938
rgrove/crass
lib/crass/parser.rb
Crass.Parser.consume_at_rule
def consume_at_rule(input = @tokens) rule = {} rule[:tokens] = input.collect do rule[:name] = input.consume[:value] rule[:prelude] = [] while token = input.consume node = token[:node] if node == :comment # Non-standard. next elsif node == :semicolon break elsif node === :'{' # Note: The spec says the block should _be_ the consumed simple # block, but Simon Sapin's CSS parsing tests and tinycss2 expect # only the _value_ of the consumed simple block here. I assume I'm # interpreting the spec too literally, so I'm going with the # tinycss2 behavior. rule[:block] = consume_simple_block(input)[:value] break elsif node == :simple_block && token[:start] == '{' # Note: The spec says the block should _be_ the simple block, but # Simon Sapin's CSS parsing tests and tinycss2 expect only the # _value_ of the simple block here. I assume I'm interpreting the # spec too literally, so I'm going with the tinycss2 behavior. rule[:block] = token[:value] break else input.reconsume rule[:prelude] << consume_component_value(input) end end end create_node(:at_rule, rule) end
ruby
def consume_at_rule(input = @tokens) rule = {} rule[:tokens] = input.collect do rule[:name] = input.consume[:value] rule[:prelude] = [] while token = input.consume node = token[:node] if node == :comment # Non-standard. next elsif node == :semicolon break elsif node === :'{' # Note: The spec says the block should _be_ the consumed simple # block, but Simon Sapin's CSS parsing tests and tinycss2 expect # only the _value_ of the consumed simple block here. I assume I'm # interpreting the spec too literally, so I'm going with the # tinycss2 behavior. rule[:block] = consume_simple_block(input)[:value] break elsif node == :simple_block && token[:start] == '{' # Note: The spec says the block should _be_ the simple block, but # Simon Sapin's CSS parsing tests and tinycss2 expect only the # _value_ of the simple block here. I assume I'm interpreting the # spec too literally, so I'm going with the tinycss2 behavior. rule[:block] = token[:value] break else input.reconsume rule[:prelude] << consume_component_value(input) end end end create_node(:at_rule, rule) end
[ "def", "consume_at_rule", "(", "input", "=", "@tokens", ")", "rule", "=", "{", "}", "rule", "[", ":tokens", "]", "=", "input", ".", "collect", "do", "rule", "[", ":name", "]", "=", "input", ".", "consume", "[", ":value", "]", "rule", "[", ":prelude", "]", "=", "[", "]", "while", "token", "=", "input", ".", "consume", "node", "=", "token", "[", ":node", "]", "if", "node", "==", ":comment", "# Non-standard.", "next", "elsif", "node", "==", ":semicolon", "break", "elsif", "node", "===", ":'", "'", "# Note: The spec says the block should _be_ the consumed simple", "# block, but Simon Sapin's CSS parsing tests and tinycss2 expect", "# only the _value_ of the consumed simple block here. I assume I'm", "# interpreting the spec too literally, so I'm going with the", "# tinycss2 behavior.", "rule", "[", ":block", "]", "=", "consume_simple_block", "(", "input", ")", "[", ":value", "]", "break", "elsif", "node", "==", ":simple_block", "&&", "token", "[", ":start", "]", "==", "'{'", "# Note: The spec says the block should _be_ the simple block, but", "# Simon Sapin's CSS parsing tests and tinycss2 expect only the", "# _value_ of the simple block here. I assume I'm interpreting the", "# spec too literally, so I'm going with the tinycss2 behavior.", "rule", "[", ":block", "]", "=", "token", "[", ":value", "]", "break", "else", "input", ".", "reconsume", "rule", "[", ":prelude", "]", "<<", "consume_component_value", "(", "input", ")", "end", "end", "end", "create_node", "(", ":at_rule", ",", "rule", ")", "end" ]
Initializes a parser based on the given _input_, which may be a CSS string or an array of tokens. See {Tokenizer#initialize} for _options_. Consumes an at-rule and returns it. 5.4.2. http://dev.w3.org/csswg/css-syntax-3/#consume-at-rule
[ "Initializes", "a", "parser", "based", "on", "the", "given", "_input_", "which", "may", "be", "a", "CSS", "string", "or", "an", "array", "of", "tokens", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L137-L178
939
rgrove/crass
lib/crass/parser.rb
Crass.Parser.consume_component_value
def consume_component_value(input = @tokens) return nil unless token = input.consume case token[:node] when :'{', :'[', :'(' consume_simple_block(input) when :function if token.key?(:name) # This is a parsed function, not a function token. This step isn't # mentioned in the spec, but it's necessary to avoid re-parsing # functions that have already been parsed. token else consume_function(input) end else token end end
ruby
def consume_component_value(input = @tokens) return nil unless token = input.consume case token[:node] when :'{', :'[', :'(' consume_simple_block(input) when :function if token.key?(:name) # This is a parsed function, not a function token. This step isn't # mentioned in the spec, but it's necessary to avoid re-parsing # functions that have already been parsed. token else consume_function(input) end else token end end
[ "def", "consume_component_value", "(", "input", "=", "@tokens", ")", "return", "nil", "unless", "token", "=", "input", ".", "consume", "case", "token", "[", ":node", "]", "when", ":'", "'", ",", ":'", "'", ",", ":'", "'", "consume_simple_block", "(", "input", ")", "when", ":function", "if", "token", ".", "key?", "(", ":name", ")", "# This is a parsed function, not a function token. This step isn't", "# mentioned in the spec, but it's necessary to avoid re-parsing", "# functions that have already been parsed.", "token", "else", "consume_function", "(", "input", ")", "end", "else", "token", "end", "end" ]
Consumes a component value and returns it, or `nil` if there are no more tokens. 5.4.6. http://dev.w3.org/csswg/css-syntax-3/#consume-a-component-value
[ "Consumes", "a", "component", "value", "and", "returns", "it", "or", "nil", "if", "there", "are", "no", "more", "tokens", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L184-L204
940
rgrove/crass
lib/crass/parser.rb
Crass.Parser.consume_declaration
def consume_declaration(input = @tokens) declaration = {} value = [] declaration[:tokens] = input.collect do declaration[:name] = input.consume[:value] next_token = input.peek while next_token && next_token[:node] == :whitespace input.consume next_token = input.peek end unless next_token && next_token[:node] == :colon # Parse error. # # Note: The spec explicitly says to return nothing here, but Simon # Sapin's CSS parsing tests expect an error node. return create_node(:error, :value => 'invalid') end input.consume until input.peek.nil? value << consume_component_value(input) end end # Look for !important. important_tokens = value.reject {|token| node = token[:node] node == :whitespace || node == :comment || node == :semicolon }.last(2) if important_tokens.size == 2 && important_tokens[0][:node] == :delim && important_tokens[0][:value] == '!' && important_tokens[1][:node] == :ident && important_tokens[1][:value].downcase == 'important' declaration[:important] = true excl_index = value.index(important_tokens[0]) # Technically the spec doesn't require us to trim trailing tokens after # the !important, but Simon Sapin's CSS parsing tests expect it and # tinycss2 does it, so we'll go along with the cool kids. value.slice!(excl_index, value.size - excl_index) else declaration[:important] = false end declaration[:value] = value create_node(:declaration, declaration) end
ruby
def consume_declaration(input = @tokens) declaration = {} value = [] declaration[:tokens] = input.collect do declaration[:name] = input.consume[:value] next_token = input.peek while next_token && next_token[:node] == :whitespace input.consume next_token = input.peek end unless next_token && next_token[:node] == :colon # Parse error. # # Note: The spec explicitly says to return nothing here, but Simon # Sapin's CSS parsing tests expect an error node. return create_node(:error, :value => 'invalid') end input.consume until input.peek.nil? value << consume_component_value(input) end end # Look for !important. important_tokens = value.reject {|token| node = token[:node] node == :whitespace || node == :comment || node == :semicolon }.last(2) if important_tokens.size == 2 && important_tokens[0][:node] == :delim && important_tokens[0][:value] == '!' && important_tokens[1][:node] == :ident && important_tokens[1][:value].downcase == 'important' declaration[:important] = true excl_index = value.index(important_tokens[0]) # Technically the spec doesn't require us to trim trailing tokens after # the !important, but Simon Sapin's CSS parsing tests expect it and # tinycss2 does it, so we'll go along with the cool kids. value.slice!(excl_index, value.size - excl_index) else declaration[:important] = false end declaration[:value] = value create_node(:declaration, declaration) end
[ "def", "consume_declaration", "(", "input", "=", "@tokens", ")", "declaration", "=", "{", "}", "value", "=", "[", "]", "declaration", "[", ":tokens", "]", "=", "input", ".", "collect", "do", "declaration", "[", ":name", "]", "=", "input", ".", "consume", "[", ":value", "]", "next_token", "=", "input", ".", "peek", "while", "next_token", "&&", "next_token", "[", ":node", "]", "==", ":whitespace", "input", ".", "consume", "next_token", "=", "input", ".", "peek", "end", "unless", "next_token", "&&", "next_token", "[", ":node", "]", "==", ":colon", "# Parse error.", "#", "# Note: The spec explicitly says to return nothing here, but Simon", "# Sapin's CSS parsing tests expect an error node.", "return", "create_node", "(", ":error", ",", ":value", "=>", "'invalid'", ")", "end", "input", ".", "consume", "until", "input", ".", "peek", ".", "nil?", "value", "<<", "consume_component_value", "(", "input", ")", "end", "end", "# Look for !important.", "important_tokens", "=", "value", ".", "reject", "{", "|", "token", "|", "node", "=", "token", "[", ":node", "]", "node", "==", ":whitespace", "||", "node", "==", ":comment", "||", "node", "==", ":semicolon", "}", ".", "last", "(", "2", ")", "if", "important_tokens", ".", "size", "==", "2", "&&", "important_tokens", "[", "0", "]", "[", ":node", "]", "==", ":delim", "&&", "important_tokens", "[", "0", "]", "[", ":value", "]", "==", "'!'", "&&", "important_tokens", "[", "1", "]", "[", ":node", "]", "==", ":ident", "&&", "important_tokens", "[", "1", "]", "[", ":value", "]", ".", "downcase", "==", "'important'", "declaration", "[", ":important", "]", "=", "true", "excl_index", "=", "value", ".", "index", "(", "important_tokens", "[", "0", "]", ")", "# Technically the spec doesn't require us to trim trailing tokens after", "# the !important, but Simon Sapin's CSS parsing tests expect it and", "# tinycss2 does it, so we'll go along with the cool kids.", "value", ".", "slice!", "(", "excl_index", ",", "value", ".", "size", "-", "excl_index", ")", "else", "declaration", "[", ":important", "]", "=", "false", "end", "declaration", "[", ":value", "]", "=", "value", "create_node", "(", ":declaration", ",", "declaration", ")", "end" ]
Consumes a declaration and returns it, or `nil` on parse error. 5.4.5. http://dev.w3.org/csswg/css-syntax-3/#consume-a-declaration
[ "Consumes", "a", "declaration", "and", "returns", "it", "or", "nil", "on", "parse", "error", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L209-L263
941
rgrove/crass
lib/crass/parser.rb
Crass.Parser.consume_declarations
def consume_declarations(input = @tokens, options = {}) declarations = [] while token = input.consume case token[:node] # Non-standard: Preserve comments, semicolons, and whitespace. when :comment, :semicolon, :whitespace declarations << token unless options[:strict] when :at_keyword # When parsing a style rule, this is a parse error. Otherwise it's # not. input.reconsume declarations << consume_at_rule(input) when :ident decl_tokens = [token] while next_token = input.peek break if next_token[:node] == :semicolon decl_tokens << consume_component_value(input) end if decl = consume_declaration(TokenScanner.new(decl_tokens)) declarations << decl end else # Parse error (invalid property name, etc.). # # Note: The spec doesn't say we should append anything to the list of # declarations here, but Simon Sapin's CSS parsing tests expect an # error node. declarations << create_node(:error, :value => 'invalid') input.reconsume while next_token = input.peek break if next_token[:node] == :semicolon consume_component_value(input) end end end declarations end
ruby
def consume_declarations(input = @tokens, options = {}) declarations = [] while token = input.consume case token[:node] # Non-standard: Preserve comments, semicolons, and whitespace. when :comment, :semicolon, :whitespace declarations << token unless options[:strict] when :at_keyword # When parsing a style rule, this is a parse error. Otherwise it's # not. input.reconsume declarations << consume_at_rule(input) when :ident decl_tokens = [token] while next_token = input.peek break if next_token[:node] == :semicolon decl_tokens << consume_component_value(input) end if decl = consume_declaration(TokenScanner.new(decl_tokens)) declarations << decl end else # Parse error (invalid property name, etc.). # # Note: The spec doesn't say we should append anything to the list of # declarations here, but Simon Sapin's CSS parsing tests expect an # error node. declarations << create_node(:error, :value => 'invalid') input.reconsume while next_token = input.peek break if next_token[:node] == :semicolon consume_component_value(input) end end end declarations end
[ "def", "consume_declarations", "(", "input", "=", "@tokens", ",", "options", "=", "{", "}", ")", "declarations", "=", "[", "]", "while", "token", "=", "input", ".", "consume", "case", "token", "[", ":node", "]", "# Non-standard: Preserve comments, semicolons, and whitespace.", "when", ":comment", ",", ":semicolon", ",", ":whitespace", "declarations", "<<", "token", "unless", "options", "[", ":strict", "]", "when", ":at_keyword", "# When parsing a style rule, this is a parse error. Otherwise it's", "# not.", "input", ".", "reconsume", "declarations", "<<", "consume_at_rule", "(", "input", ")", "when", ":ident", "decl_tokens", "=", "[", "token", "]", "while", "next_token", "=", "input", ".", "peek", "break", "if", "next_token", "[", ":node", "]", "==", ":semicolon", "decl_tokens", "<<", "consume_component_value", "(", "input", ")", "end", "if", "decl", "=", "consume_declaration", "(", "TokenScanner", ".", "new", "(", "decl_tokens", ")", ")", "declarations", "<<", "decl", "end", "else", "# Parse error (invalid property name, etc.).", "#", "# Note: The spec doesn't say we should append anything to the list of", "# declarations here, but Simon Sapin's CSS parsing tests expect an", "# error node.", "declarations", "<<", "create_node", "(", ":error", ",", ":value", "=>", "'invalid'", ")", "input", ".", "reconsume", "while", "next_token", "=", "input", ".", "peek", "break", "if", "next_token", "[", ":node", "]", "==", ":semicolon", "consume_component_value", "(", "input", ")", "end", "end", "end", "declarations", "end" ]
Consumes a list of declarations and returns them. By default, the returned list may include `:comment`, `:semicolon`, and `:whitespace` nodes, which is non-standard. Options: * **:strict** - Set to `true` to exclude non-standard `:comment`, `:semicolon`, and `:whitespace` nodes. 5.4.4. http://dev.w3.org/csswg/css-syntax/#consume-a-list-of-declarations
[ "Consumes", "a", "list", "of", "declarations", "and", "returns", "them", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L276-L321
942
rgrove/crass
lib/crass/parser.rb
Crass.Parser.consume_function
def consume_function(input = @tokens) function = { :name => input.current[:value], :value => [], :tokens => [input.current] # Non-standard, used for serialization. } function[:tokens].concat(input.collect { while token = input.consume case token[:node] when :')' break # Non-standard. when :comment next else input.reconsume function[:value] << consume_component_value(input) end end }) create_node(:function, function) end
ruby
def consume_function(input = @tokens) function = { :name => input.current[:value], :value => [], :tokens => [input.current] # Non-standard, used for serialization. } function[:tokens].concat(input.collect { while token = input.consume case token[:node] when :')' break # Non-standard. when :comment next else input.reconsume function[:value] << consume_component_value(input) end end }) create_node(:function, function) end
[ "def", "consume_function", "(", "input", "=", "@tokens", ")", "function", "=", "{", ":name", "=>", "input", ".", "current", "[", ":value", "]", ",", ":value", "=>", "[", "]", ",", ":tokens", "=>", "[", "input", ".", "current", "]", "# Non-standard, used for serialization.", "}", "function", "[", ":tokens", "]", ".", "concat", "(", "input", ".", "collect", "{", "while", "token", "=", "input", ".", "consume", "case", "token", "[", ":node", "]", "when", ":'", "'", "break", "# Non-standard.", "when", ":comment", "next", "else", "input", ".", "reconsume", "function", "[", ":value", "]", "<<", "consume_component_value", "(", "input", ")", "end", "end", "}", ")", "create_node", "(", ":function", ",", "function", ")", "end" ]
Consumes a function and returns it. 5.4.8. http://dev.w3.org/csswg/css-syntax-3/#consume-a-function
[ "Consumes", "a", "function", "and", "returns", "it", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L326-L351
943
rgrove/crass
lib/crass/parser.rb
Crass.Parser.consume_qualified_rule
def consume_qualified_rule(input = @tokens) rule = {:prelude => []} rule[:tokens] = input.collect do while true unless token = input.consume # Parse error. # # Note: The spec explicitly says to return nothing here, but Simon # Sapin's CSS parsing tests expect an error node. return create_node(:error, :value => 'invalid') end if token[:node] == :'{' # Note: The spec says the block should _be_ the consumed simple # block, but Simon Sapin's CSS parsing tests and tinycss2 expect # only the _value_ of the consumed simple block here. I assume I'm # interpreting the spec too literally, so I'm going with the # tinycss2 behavior. rule[:block] = consume_simple_block(input)[:value] break elsif token[:node] == :simple_block && token[:start] == '{' # Note: The spec says the block should _be_ the simple block, but # Simon Sapin's CSS parsing tests and tinycss2 expect only the # _value_ of the simple block here. I assume I'm interpreting the # spec too literally, so I'm going with the tinycss2 behavior. rule[:block] = token[:value] break else input.reconsume rule[:prelude] << consume_component_value(input) end end end create_node(:qualified_rule, rule) end
ruby
def consume_qualified_rule(input = @tokens) rule = {:prelude => []} rule[:tokens] = input.collect do while true unless token = input.consume # Parse error. # # Note: The spec explicitly says to return nothing here, but Simon # Sapin's CSS parsing tests expect an error node. return create_node(:error, :value => 'invalid') end if token[:node] == :'{' # Note: The spec says the block should _be_ the consumed simple # block, but Simon Sapin's CSS parsing tests and tinycss2 expect # only the _value_ of the consumed simple block here. I assume I'm # interpreting the spec too literally, so I'm going with the # tinycss2 behavior. rule[:block] = consume_simple_block(input)[:value] break elsif token[:node] == :simple_block && token[:start] == '{' # Note: The spec says the block should _be_ the simple block, but # Simon Sapin's CSS parsing tests and tinycss2 expect only the # _value_ of the simple block here. I assume I'm interpreting the # spec too literally, so I'm going with the tinycss2 behavior. rule[:block] = token[:value] break else input.reconsume rule[:prelude] << consume_component_value(input) end end end create_node(:qualified_rule, rule) end
[ "def", "consume_qualified_rule", "(", "input", "=", "@tokens", ")", "rule", "=", "{", ":prelude", "=>", "[", "]", "}", "rule", "[", ":tokens", "]", "=", "input", ".", "collect", "do", "while", "true", "unless", "token", "=", "input", ".", "consume", "# Parse error.", "#", "# Note: The spec explicitly says to return nothing here, but Simon", "# Sapin's CSS parsing tests expect an error node.", "return", "create_node", "(", ":error", ",", ":value", "=>", "'invalid'", ")", "end", "if", "token", "[", ":node", "]", "==", ":'", "'", "# Note: The spec says the block should _be_ the consumed simple", "# block, but Simon Sapin's CSS parsing tests and tinycss2 expect", "# only the _value_ of the consumed simple block here. I assume I'm", "# interpreting the spec too literally, so I'm going with the", "# tinycss2 behavior.", "rule", "[", ":block", "]", "=", "consume_simple_block", "(", "input", ")", "[", ":value", "]", "break", "elsif", "token", "[", ":node", "]", "==", ":simple_block", "&&", "token", "[", ":start", "]", "==", "'{'", "# Note: The spec says the block should _be_ the simple block, but", "# Simon Sapin's CSS parsing tests and tinycss2 expect only the", "# _value_ of the simple block here. I assume I'm interpreting the", "# spec too literally, so I'm going with the tinycss2 behavior.", "rule", "[", ":block", "]", "=", "token", "[", ":value", "]", "break", "else", "input", ".", "reconsume", "rule", "[", ":prelude", "]", "<<", "consume_component_value", "(", "input", ")", "end", "end", "end", "create_node", "(", ":qualified_rule", ",", "rule", ")", "end" ]
Consumes a qualified rule and returns it, or `nil` if a parse error occurs. 5.4.3. http://dev.w3.org/csswg/css-syntax-3/#consume-a-qualified-rule
[ "Consumes", "a", "qualified", "rule", "and", "returns", "it", "or", "nil", "if", "a", "parse", "error", "occurs", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L357-L393
944
rgrove/crass
lib/crass/parser.rb
Crass.Parser.consume_rules
def consume_rules(flags = {}) rules = [] while token = @tokens.consume case token[:node] # Non-standard. Spec says to discard comments and whitespace, but we # keep them so we can serialize faithfully. when :comment, :whitespace rules << token when :cdc, :cdo unless flags[:top_level] @tokens.reconsume rule = consume_qualified_rule rules << rule if rule end when :at_keyword @tokens.reconsume rule = consume_at_rule rules << rule if rule else @tokens.reconsume rule = consume_qualified_rule rules << rule if rule end end rules end
ruby
def consume_rules(flags = {}) rules = [] while token = @tokens.consume case token[:node] # Non-standard. Spec says to discard comments and whitespace, but we # keep them so we can serialize faithfully. when :comment, :whitespace rules << token when :cdc, :cdo unless flags[:top_level] @tokens.reconsume rule = consume_qualified_rule rules << rule if rule end when :at_keyword @tokens.reconsume rule = consume_at_rule rules << rule if rule else @tokens.reconsume rule = consume_qualified_rule rules << rule if rule end end rules end
[ "def", "consume_rules", "(", "flags", "=", "{", "}", ")", "rules", "=", "[", "]", "while", "token", "=", "@tokens", ".", "consume", "case", "token", "[", ":node", "]", "# Non-standard. Spec says to discard comments and whitespace, but we", "# keep them so we can serialize faithfully.", "when", ":comment", ",", ":whitespace", "rules", "<<", "token", "when", ":cdc", ",", ":cdo", "unless", "flags", "[", ":top_level", "]", "@tokens", ".", "reconsume", "rule", "=", "consume_qualified_rule", "rules", "<<", "rule", "if", "rule", "end", "when", ":at_keyword", "@tokens", ".", "reconsume", "rule", "=", "consume_at_rule", "rules", "<<", "rule", "if", "rule", "else", "@tokens", ".", "reconsume", "rule", "=", "consume_qualified_rule", "rules", "<<", "rule", "if", "rule", "end", "end", "rules", "end" ]
Consumes a list of rules and returns them. 5.4.1. http://dev.w3.org/csswg/css-syntax/#consume-a-list-of-rules
[ "Consumes", "a", "list", "of", "rules", "and", "returns", "them", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L398-L428
945
rgrove/crass
lib/crass/parser.rb
Crass.Parser.consume_simple_block
def consume_simple_block(input = @tokens) start_token = input.current[:node] end_token = BLOCK_END_TOKENS[start_token] block = { :start => start_token.to_s, :end => end_token.to_s, :value => [], :tokens => [input.current] # Non-standard. Used for serialization. } block[:tokens].concat(input.collect do while token = input.consume break if token[:node] == end_token input.reconsume block[:value] << consume_component_value(input) end end) create_node(:simple_block, block) end
ruby
def consume_simple_block(input = @tokens) start_token = input.current[:node] end_token = BLOCK_END_TOKENS[start_token] block = { :start => start_token.to_s, :end => end_token.to_s, :value => [], :tokens => [input.current] # Non-standard. Used for serialization. } block[:tokens].concat(input.collect do while token = input.consume break if token[:node] == end_token input.reconsume block[:value] << consume_component_value(input) end end) create_node(:simple_block, block) end
[ "def", "consume_simple_block", "(", "input", "=", "@tokens", ")", "start_token", "=", "input", ".", "current", "[", ":node", "]", "end_token", "=", "BLOCK_END_TOKENS", "[", "start_token", "]", "block", "=", "{", ":start", "=>", "start_token", ".", "to_s", ",", ":end", "=>", "end_token", ".", "to_s", ",", ":value", "=>", "[", "]", ",", ":tokens", "=>", "[", "input", ".", "current", "]", "# Non-standard. Used for serialization.", "}", "block", "[", ":tokens", "]", ".", "concat", "(", "input", ".", "collect", "do", "while", "token", "=", "input", ".", "consume", "break", "if", "token", "[", ":node", "]", "==", "end_token", "input", ".", "reconsume", "block", "[", ":value", "]", "<<", "consume_component_value", "(", "input", ")", "end", "end", ")", "create_node", "(", ":simple_block", ",", "block", ")", "end" ]
Consumes and returns a simple block associated with the current input token. 5.4.7. http://dev.w3.org/csswg/css-syntax/#consume-a-simple-block
[ "Consumes", "and", "returns", "a", "simple", "block", "associated", "with", "the", "current", "input", "token", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L434-L455
946
rgrove/crass
lib/crass/parser.rb
Crass.Parser.parse_component_value
def parse_component_value(input = @tokens) input = TokenScanner.new(input) unless input.is_a?(TokenScanner) while input.peek && input.peek[:node] == :whitespace input.consume end if input.peek.nil? return create_node(:error, :value => 'empty') end value = consume_component_value(input) while input.peek && input.peek[:node] == :whitespace input.consume end if input.peek.nil? value else create_node(:error, :value => 'extra-input') end end
ruby
def parse_component_value(input = @tokens) input = TokenScanner.new(input) unless input.is_a?(TokenScanner) while input.peek && input.peek[:node] == :whitespace input.consume end if input.peek.nil? return create_node(:error, :value => 'empty') end value = consume_component_value(input) while input.peek && input.peek[:node] == :whitespace input.consume end if input.peek.nil? value else create_node(:error, :value => 'extra-input') end end
[ "def", "parse_component_value", "(", "input", "=", "@tokens", ")", "input", "=", "TokenScanner", ".", "new", "(", "input", ")", "unless", "input", ".", "is_a?", "(", "TokenScanner", ")", "while", "input", ".", "peek", "&&", "input", ".", "peek", "[", ":node", "]", "==", ":whitespace", "input", ".", "consume", "end", "if", "input", ".", "peek", ".", "nil?", "return", "create_node", "(", ":error", ",", ":value", "=>", "'empty'", ")", "end", "value", "=", "consume_component_value", "(", "input", ")", "while", "input", ".", "peek", "&&", "input", ".", "peek", "[", ":node", "]", "==", ":whitespace", "input", ".", "consume", "end", "if", "input", ".", "peek", ".", "nil?", "value", "else", "create_node", "(", ":error", ",", ":value", "=>", "'extra-input'", ")", "end", "end" ]
Parses a single component value and returns it. 5.3.7. http://dev.w3.org/csswg/css-syntax-3/#parse-a-component-value
[ "Parses", "a", "single", "component", "value", "and", "returns", "it", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L483-L505
947
rgrove/crass
lib/crass/parser.rb
Crass.Parser.parse_component_values
def parse_component_values(input = @tokens) input = TokenScanner.new(input) unless input.is_a?(TokenScanner) tokens = [] while token = consume_component_value(input) tokens << token end tokens end
ruby
def parse_component_values(input = @tokens) input = TokenScanner.new(input) unless input.is_a?(TokenScanner) tokens = [] while token = consume_component_value(input) tokens << token end tokens end
[ "def", "parse_component_values", "(", "input", "=", "@tokens", ")", "input", "=", "TokenScanner", ".", "new", "(", "input", ")", "unless", "input", ".", "is_a?", "(", "TokenScanner", ")", "tokens", "=", "[", "]", "while", "token", "=", "consume_component_value", "(", "input", ")", "tokens", "<<", "token", "end", "tokens", "end" ]
Parses a list of component values and returns an array of parsed tokens. 5.3.8. http://dev.w3.org/csswg/css-syntax/#parse-a-list-of-component-values
[ "Parses", "a", "list", "of", "component", "values", "and", "returns", "an", "array", "of", "parsed", "tokens", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L510-L519
948
rgrove/crass
lib/crass/parser.rb
Crass.Parser.parse_declaration
def parse_declaration(input = @tokens) input = TokenScanner.new(input) unless input.is_a?(TokenScanner) while input.peek && input.peek[:node] == :whitespace input.consume end if input.peek.nil? # Syntax error. return create_node(:error, :value => 'empty') elsif input.peek[:node] != :ident # Syntax error. return create_node(:error, :value => 'invalid') end if decl = consume_declaration(input) return decl end # Syntax error. create_node(:error, :value => 'invalid') end
ruby
def parse_declaration(input = @tokens) input = TokenScanner.new(input) unless input.is_a?(TokenScanner) while input.peek && input.peek[:node] == :whitespace input.consume end if input.peek.nil? # Syntax error. return create_node(:error, :value => 'empty') elsif input.peek[:node] != :ident # Syntax error. return create_node(:error, :value => 'invalid') end if decl = consume_declaration(input) return decl end # Syntax error. create_node(:error, :value => 'invalid') end
[ "def", "parse_declaration", "(", "input", "=", "@tokens", ")", "input", "=", "TokenScanner", ".", "new", "(", "input", ")", "unless", "input", ".", "is_a?", "(", "TokenScanner", ")", "while", "input", ".", "peek", "&&", "input", ".", "peek", "[", ":node", "]", "==", ":whitespace", "input", ".", "consume", "end", "if", "input", ".", "peek", ".", "nil?", "# Syntax error.", "return", "create_node", "(", ":error", ",", ":value", "=>", "'empty'", ")", "elsif", "input", ".", "peek", "[", ":node", "]", "!=", ":ident", "# Syntax error.", "return", "create_node", "(", ":error", ",", ":value", "=>", "'invalid'", ")", "end", "if", "decl", "=", "consume_declaration", "(", "input", ")", "return", "decl", "end", "# Syntax error.", "create_node", "(", ":error", ",", ":value", "=>", "'invalid'", ")", "end" ]
Parses a single declaration and returns it. 5.3.5. http://dev.w3.org/csswg/css-syntax/#parse-a-declaration
[ "Parses", "a", "single", "declaration", "and", "returns", "it", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L524-L545
949
rgrove/crass
lib/crass/parser.rb
Crass.Parser.parse_declarations
def parse_declarations(input = @tokens, options = {}) input = TokenScanner.new(input) unless input.is_a?(TokenScanner) consume_declarations(input, options) end
ruby
def parse_declarations(input = @tokens, options = {}) input = TokenScanner.new(input) unless input.is_a?(TokenScanner) consume_declarations(input, options) end
[ "def", "parse_declarations", "(", "input", "=", "@tokens", ",", "options", "=", "{", "}", ")", "input", "=", "TokenScanner", ".", "new", "(", "input", ")", "unless", "input", ".", "is_a?", "(", "TokenScanner", ")", "consume_declarations", "(", "input", ",", "options", ")", "end" ]
Parses a list of declarations and returns them. See {#consume_declarations} for _options_. 5.3.6. http://dev.w3.org/csswg/css-syntax/#parse-a-list-of-declarations
[ "Parses", "a", "list", "of", "declarations", "and", "returns", "them", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L552-L555
950
rgrove/crass
lib/crass/parser.rb
Crass.Parser.parse_rule
def parse_rule(input = @tokens) input = TokenScanner.new(input) unless input.is_a?(TokenScanner) while input.peek && input.peek[:node] == :whitespace input.consume end if input.peek.nil? # Syntax error. return create_node(:error, :value => 'empty') elsif input.peek[:node] == :at_keyword rule = consume_at_rule(input) else rule = consume_qualified_rule(input) end while input.peek && input.peek[:node] == :whitespace input.consume end if input.peek.nil? rule else # Syntax error. create_node(:error, :value => 'extra-input') end end
ruby
def parse_rule(input = @tokens) input = TokenScanner.new(input) unless input.is_a?(TokenScanner) while input.peek && input.peek[:node] == :whitespace input.consume end if input.peek.nil? # Syntax error. return create_node(:error, :value => 'empty') elsif input.peek[:node] == :at_keyword rule = consume_at_rule(input) else rule = consume_qualified_rule(input) end while input.peek && input.peek[:node] == :whitespace input.consume end if input.peek.nil? rule else # Syntax error. create_node(:error, :value => 'extra-input') end end
[ "def", "parse_rule", "(", "input", "=", "@tokens", ")", "input", "=", "TokenScanner", ".", "new", "(", "input", ")", "unless", "input", ".", "is_a?", "(", "TokenScanner", ")", "while", "input", ".", "peek", "&&", "input", ".", "peek", "[", ":node", "]", "==", ":whitespace", "input", ".", "consume", "end", "if", "input", ".", "peek", ".", "nil?", "# Syntax error.", "return", "create_node", "(", ":error", ",", ":value", "=>", "'empty'", ")", "elsif", "input", ".", "peek", "[", ":node", "]", "==", ":at_keyword", "rule", "=", "consume_at_rule", "(", "input", ")", "else", "rule", "=", "consume_qualified_rule", "(", "input", ")", "end", "while", "input", ".", "peek", "&&", "input", ".", "peek", "[", ":node", "]", "==", ":whitespace", "input", ".", "consume", "end", "if", "input", ".", "peek", ".", "nil?", "rule", "else", "# Syntax error.", "create_node", "(", ":error", ",", ":value", "=>", "'extra-input'", ")", "end", "end" ]
Parses a single rule and returns it. 5.3.4. http://dev.w3.org/csswg/css-syntax-3/#parse-a-rule
[ "Parses", "a", "single", "rule", "and", "returns", "it", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L586-L612
951
rgrove/crass
lib/crass/parser.rb
Crass.Parser.parse_value
def parse_value(nodes) nodes = [nodes] unless nodes.is_a?(Array) string = String.new nodes.each do |node| case node[:node] when :comment, :semicolon next when :at_keyword, :ident string << node[:value] when :function if node[:value].is_a?(String) string << node[:value] string << '(' else string << parse_value(node[:tokens]) end else if node.key?(:raw) string << node[:raw] elsif node.key?(:tokens) string << parse_value(node[:tokens]) end end end string.strip end
ruby
def parse_value(nodes) nodes = [nodes] unless nodes.is_a?(Array) string = String.new nodes.each do |node| case node[:node] when :comment, :semicolon next when :at_keyword, :ident string << node[:value] when :function if node[:value].is_a?(String) string << node[:value] string << '(' else string << parse_value(node[:tokens]) end else if node.key?(:raw) string << node[:raw] elsif node.key?(:tokens) string << parse_value(node[:tokens]) end end end string.strip end
[ "def", "parse_value", "(", "nodes", ")", "nodes", "=", "[", "nodes", "]", "unless", "nodes", ".", "is_a?", "(", "Array", ")", "string", "=", "String", ".", "new", "nodes", ".", "each", "do", "|", "node", "|", "case", "node", "[", ":node", "]", "when", ":comment", ",", ":semicolon", "next", "when", ":at_keyword", ",", ":ident", "string", "<<", "node", "[", ":value", "]", "when", ":function", "if", "node", "[", ":value", "]", ".", "is_a?", "(", "String", ")", "string", "<<", "node", "[", ":value", "]", "string", "<<", "'('", "else", "string", "<<", "parse_value", "(", "node", "[", ":tokens", "]", ")", "end", "else", "if", "node", ".", "key?", "(", ":raw", ")", "string", "<<", "node", "[", ":raw", "]", "elsif", "node", ".", "key?", "(", ":tokens", ")", "string", "<<", "parse_value", "(", "node", "[", ":tokens", "]", ")", "end", "end", "end", "string", ".", "strip", "end" ]
Returns the unescaped value of a selector name or property declaration.
[ "Returns", "the", "unescaped", "value", "of", "a", "selector", "name", "or", "property", "declaration", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/parser.rb#L615-L645
952
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.consume_bad_url
def consume_bad_url text = String.new until @s.eos? if valid_escape? text << consume_escaped elsif valid_escape?(@s.peek(2)) @s.consume text << consume_escaped else char = @s.consume if char == ')' break else text << char end end end text end
ruby
def consume_bad_url text = String.new until @s.eos? if valid_escape? text << consume_escaped elsif valid_escape?(@s.peek(2)) @s.consume text << consume_escaped else char = @s.consume if char == ')' break else text << char end end end text end
[ "def", "consume_bad_url", "text", "=", "String", ".", "new", "until", "@s", ".", "eos?", "if", "valid_escape?", "text", "<<", "consume_escaped", "elsif", "valid_escape?", "(", "@s", ".", "peek", "(", "2", ")", ")", "@s", ".", "consume", "text", "<<", "consume_escaped", "else", "char", "=", "@s", ".", "consume", "if", "char", "==", "')'", "break", "else", "text", "<<", "char", "end", "end", "end", "text", "end" ]
Consumes the remnants of a bad URL and returns the consumed text. 4.3.15. http://dev.w3.org/csswg/css-syntax/#consume-the-remnants-of-a-bad-url
[ "Consumes", "the", "remnants", "of", "a", "bad", "URL", "and", "returns", "the", "consumed", "text", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L275-L296
953
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.consume_comments
def consume_comments if @s.peek(2) == '/*' @s.consume @s.consume if text = @s.scan_until(RE_COMMENT_CLOSE) text.slice!(-2, 2) else # Parse error. text = @s.consume_rest end return create_token(:comment, :value => text) end nil end
ruby
def consume_comments if @s.peek(2) == '/*' @s.consume @s.consume if text = @s.scan_until(RE_COMMENT_CLOSE) text.slice!(-2, 2) else # Parse error. text = @s.consume_rest end return create_token(:comment, :value => text) end nil end
[ "def", "consume_comments", "if", "@s", ".", "peek", "(", "2", ")", "==", "'/*'", "@s", ".", "consume", "@s", ".", "consume", "if", "text", "=", "@s", ".", "scan_until", "(", "RE_COMMENT_CLOSE", ")", "text", ".", "slice!", "(", "-", "2", ",", "2", ")", "else", "# Parse error.", "text", "=", "@s", ".", "consume_rest", "end", "return", "create_token", "(", ":comment", ",", ":value", "=>", "text", ")", "end", "nil", "end" ]
Consumes comments and returns them, or `nil` if no comments were consumed. 4.3.2. http://dev.w3.org/csswg/css-syntax/#consume-comments
[ "Consumes", "comments", "and", "returns", "them", "or", "nil", "if", "no", "comments", "were", "consumed", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L301-L317
954
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.consume_escaped
def consume_escaped return "\ufffd" if @s.eos? if hex_str = @s.scan(RE_HEX) @s.consume if @s.peek =~ RE_WHITESPACE codepoint = hex_str.hex if codepoint == 0 || codepoint.between?(0xD800, 0xDFFF) || codepoint > 0x10FFFF return "\ufffd" else return codepoint.chr(Encoding::UTF_8) end end @s.consume end
ruby
def consume_escaped return "\ufffd" if @s.eos? if hex_str = @s.scan(RE_HEX) @s.consume if @s.peek =~ RE_WHITESPACE codepoint = hex_str.hex if codepoint == 0 || codepoint.between?(0xD800, 0xDFFF) || codepoint > 0x10FFFF return "\ufffd" else return codepoint.chr(Encoding::UTF_8) end end @s.consume end
[ "def", "consume_escaped", "return", "\"\\ufffd\"", "if", "@s", ".", "eos?", "if", "hex_str", "=", "@s", ".", "scan", "(", "RE_HEX", ")", "@s", ".", "consume", "if", "@s", ".", "peek", "=~", "RE_WHITESPACE", "codepoint", "=", "hex_str", ".", "hex", "if", "codepoint", "==", "0", "||", "codepoint", ".", "between?", "(", "0xD800", ",", "0xDFFF", ")", "||", "codepoint", ">", "0x10FFFF", "return", "\"\\ufffd\"", "else", "return", "codepoint", ".", "chr", "(", "Encoding", "::", "UTF_8", ")", "end", "end", "@s", ".", "consume", "end" ]
Consumes an escaped code point and returns its unescaped value. This method assumes that the `\` has already been consumed, and that the next character in the input has already been verified not to be a newline or EOF. 4.3.8. http://dev.w3.org/csswg/css-syntax/#consume-an-escaped-code-point
[ "Consumes", "an", "escaped", "code", "point", "and", "returns", "its", "unescaped", "value", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L326-L345
955
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.consume_ident
def consume_ident value = consume_name if @s.peek == '(' @s.consume if value.downcase == 'url' @s.consume while @s.peek(2) =~ RE_WHITESPACE_ANCHORED if @s.peek(2) =~ RE_QUOTED_URL_START create_token(:function, :value => value) else consume_url end else create_token(:function, :value => value) end else create_token(:ident, :value => value) end end
ruby
def consume_ident value = consume_name if @s.peek == '(' @s.consume if value.downcase == 'url' @s.consume while @s.peek(2) =~ RE_WHITESPACE_ANCHORED if @s.peek(2) =~ RE_QUOTED_URL_START create_token(:function, :value => value) else consume_url end else create_token(:function, :value => value) end else create_token(:ident, :value => value) end end
[ "def", "consume_ident", "value", "=", "consume_name", "if", "@s", ".", "peek", "==", "'('", "@s", ".", "consume", "if", "value", ".", "downcase", "==", "'url'", "@s", ".", "consume", "while", "@s", ".", "peek", "(", "2", ")", "=~", "RE_WHITESPACE_ANCHORED", "if", "@s", ".", "peek", "(", "2", ")", "=~", "RE_QUOTED_URL_START", "create_token", "(", ":function", ",", ":value", "=>", "value", ")", "else", "consume_url", "end", "else", "create_token", "(", ":function", ",", ":value", "=>", "value", ")", "end", "else", "create_token", "(", ":ident", ",", ":value", "=>", "value", ")", "end", "end" ]
Consumes an ident-like token and returns it. 4.3.4. http://dev.w3.org/csswg/css-syntax/#consume-an-ident-like-token
[ "Consumes", "an", "ident", "-", "like", "token", "and", "returns", "it", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L350-L370
956
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.consume_name
def consume_name result = String.new until @s.eos? if match = @s.scan(RE_NAME) result << match next end char = @s.consume if valid_escape? result << consume_escaped # Non-standard: IE * hack elsif char == '*' && @options[:preserve_hacks] result << @s.consume else @s.reconsume return result end end result end
ruby
def consume_name result = String.new until @s.eos? if match = @s.scan(RE_NAME) result << match next end char = @s.consume if valid_escape? result << consume_escaped # Non-standard: IE * hack elsif char == '*' && @options[:preserve_hacks] result << @s.consume else @s.reconsume return result end end result end
[ "def", "consume_name", "result", "=", "String", ".", "new", "until", "@s", ".", "eos?", "if", "match", "=", "@s", ".", "scan", "(", "RE_NAME", ")", "result", "<<", "match", "next", "end", "char", "=", "@s", ".", "consume", "if", "valid_escape?", "result", "<<", "consume_escaped", "# Non-standard: IE * hack", "elsif", "char", "==", "'*'", "&&", "@options", "[", ":preserve_hacks", "]", "result", "<<", "@s", ".", "consume", "else", "@s", ".", "reconsume", "return", "result", "end", "end", "result", "end" ]
Consumes a name and returns it. 4.3.12. http://dev.w3.org/csswg/css-syntax/#consume-a-name
[ "Consumes", "a", "name", "and", "returns", "it", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L375-L400
957
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.consume_numeric
def consume_numeric number = consume_number if start_identifier?(@s.peek(3)) create_token(:dimension, :repr => number[0], :type => number[2], :unit => consume_name, :value => number[1]) elsif @s.peek == '%' @s.consume create_token(:percentage, :repr => number[0], :type => number[2], :value => number[1]) else create_token(:number, :repr => number[0], :type => number[2], :value => number[1]) end end
ruby
def consume_numeric number = consume_number if start_identifier?(@s.peek(3)) create_token(:dimension, :repr => number[0], :type => number[2], :unit => consume_name, :value => number[1]) elsif @s.peek == '%' @s.consume create_token(:percentage, :repr => number[0], :type => number[2], :value => number[1]) else create_token(:number, :repr => number[0], :type => number[2], :value => number[1]) end end
[ "def", "consume_numeric", "number", "=", "consume_number", "if", "start_identifier?", "(", "@s", ".", "peek", "(", "3", ")", ")", "create_token", "(", ":dimension", ",", ":repr", "=>", "number", "[", "0", "]", ",", ":type", "=>", "number", "[", "2", "]", ",", ":unit", "=>", "consume_name", ",", ":value", "=>", "number", "[", "1", "]", ")", "elsif", "@s", ".", "peek", "==", "'%'", "@s", ".", "consume", "create_token", "(", ":percentage", ",", ":repr", "=>", "number", "[", "0", "]", ",", ":type", "=>", "number", "[", "2", "]", ",", ":value", "=>", "number", "[", "1", "]", ")", "else", "create_token", "(", ":number", ",", ":repr", "=>", "number", "[", "0", "]", ",", ":type", "=>", "number", "[", "2", "]", ",", ":value", "=>", "number", "[", "1", "]", ")", "end", "end" ]
Consumes a numeric token and returns it. 4.3.3. http://dev.w3.org/csswg/css-syntax/#consume-a-numeric-token
[ "Consumes", "a", "numeric", "token", "and", "returns", "it", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L430-L454
958
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.consume_string
def consume_string(ending = nil) ending = @s.current if ending.nil? value = String.new until @s.eos? case char = @s.consume when ending break when "\n" # Parse error. @s.reconsume return create_token(:bad_string, :error => true, :value => value) when '\\' case @s.peek when '' # End of the input, so do nothing. next when "\n" @s.consume else value << consume_escaped end else value << char end end create_token(:string, :value => value) end
ruby
def consume_string(ending = nil) ending = @s.current if ending.nil? value = String.new until @s.eos? case char = @s.consume when ending break when "\n" # Parse error. @s.reconsume return create_token(:bad_string, :error => true, :value => value) when '\\' case @s.peek when '' # End of the input, so do nothing. next when "\n" @s.consume else value << consume_escaped end else value << char end end create_token(:string, :value => value) end
[ "def", "consume_string", "(", "ending", "=", "nil", ")", "ending", "=", "@s", ".", "current", "if", "ending", ".", "nil?", "value", "=", "String", ".", "new", "until", "@s", ".", "eos?", "case", "char", "=", "@s", ".", "consume", "when", "ending", "break", "when", "\"\\n\"", "# Parse error.", "@s", ".", "reconsume", "return", "create_token", "(", ":bad_string", ",", ":error", "=>", "true", ",", ":value", "=>", "value", ")", "when", "'\\\\'", "case", "@s", ".", "peek", "when", "''", "# End of the input, so do nothing.", "next", "when", "\"\\n\"", "@s", ".", "consume", "else", "value", "<<", "consume_escaped", "end", "else", "value", "<<", "char", "end", "end", "create_token", "(", ":string", ",", ":value", "=>", "value", ")", "end" ]
Consumes a string token that ends at the given character, and returns the token. 4.3.5. http://dev.w3.org/csswg/css-syntax/#consume-a-string-token
[ "Consumes", "a", "string", "token", "that", "ends", "at", "the", "given", "character", "and", "returns", "the", "token", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L460-L495
959
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.consume_unicode_range
def consume_unicode_range value = @s.scan(RE_HEX) || String.new while value.length < 6 break unless @s.peek == '?' value << @s.consume end range = {} if value.include?('?') range[:start] = value.gsub('?', '0').hex range[:end] = value.gsub('?', 'F').hex return create_token(:unicode_range, range) end range[:start] = value.hex if @s.peek(2) =~ RE_UNICODE_RANGE_END @s.consume range[:end] = (@s.scan(RE_HEX) || '').hex else range[:end] = range[:start] end create_token(:unicode_range, range) end
ruby
def consume_unicode_range value = @s.scan(RE_HEX) || String.new while value.length < 6 break unless @s.peek == '?' value << @s.consume end range = {} if value.include?('?') range[:start] = value.gsub('?', '0').hex range[:end] = value.gsub('?', 'F').hex return create_token(:unicode_range, range) end range[:start] = value.hex if @s.peek(2) =~ RE_UNICODE_RANGE_END @s.consume range[:end] = (@s.scan(RE_HEX) || '').hex else range[:end] = range[:start] end create_token(:unicode_range, range) end
[ "def", "consume_unicode_range", "value", "=", "@s", ".", "scan", "(", "RE_HEX", ")", "||", "String", ".", "new", "while", "value", ".", "length", "<", "6", "break", "unless", "@s", ".", "peek", "==", "'?'", "value", "<<", "@s", ".", "consume", "end", "range", "=", "{", "}", "if", "value", ".", "include?", "(", "'?'", ")", "range", "[", ":start", "]", "=", "value", ".", "gsub", "(", "'?'", ",", "'0'", ")", ".", "hex", "range", "[", ":end", "]", "=", "value", ".", "gsub", "(", "'?'", ",", "'F'", ")", ".", "hex", "return", "create_token", "(", ":unicode_range", ",", "range", ")", "end", "range", "[", ":start", "]", "=", "value", ".", "hex", "if", "@s", ".", "peek", "(", "2", ")", "=~", "RE_UNICODE_RANGE_END", "@s", ".", "consume", "range", "[", ":end", "]", "=", "(", "@s", ".", "scan", "(", "RE_HEX", ")", "||", "''", ")", ".", "hex", "else", "range", "[", ":end", "]", "=", "range", "[", ":start", "]", "end", "create_token", "(", ":unicode_range", ",", "range", ")", "end" ]
Consumes a Unicode range token and returns it. Assumes the initial "u+" or "U+" has already been consumed. 4.3.7. http://dev.w3.org/csswg/css-syntax/#consume-a-unicode-range-token
[ "Consumes", "a", "Unicode", "range", "token", "and", "returns", "it", ".", "Assumes", "the", "initial", "u", "+", "or", "U", "+", "has", "already", "been", "consumed", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L501-L527
960
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.consume_url
def consume_url value = String.new @s.scan(RE_WHITESPACE) until @s.eos? case char = @s.consume when ')' break when RE_WHITESPACE @s.scan(RE_WHITESPACE) if @s.eos? || @s.peek == ')' @s.consume break else return create_token(:bad_url, :value => value + consume_bad_url) end when '"', "'", '(', RE_NON_PRINTABLE # Parse error. return create_token(:bad_url, :error => true, :value => value + consume_bad_url) when '\\' if valid_escape? value << consume_escaped else # Parse error. return create_token(:bad_url, :error => true, :value => value + consume_bad_url ) end else value << char end end create_token(:url, :value => value) end
ruby
def consume_url value = String.new @s.scan(RE_WHITESPACE) until @s.eos? case char = @s.consume when ')' break when RE_WHITESPACE @s.scan(RE_WHITESPACE) if @s.eos? || @s.peek == ')' @s.consume break else return create_token(:bad_url, :value => value + consume_bad_url) end when '"', "'", '(', RE_NON_PRINTABLE # Parse error. return create_token(:bad_url, :error => true, :value => value + consume_bad_url) when '\\' if valid_escape? value << consume_escaped else # Parse error. return create_token(:bad_url, :error => true, :value => value + consume_bad_url ) end else value << char end end create_token(:url, :value => value) end
[ "def", "consume_url", "value", "=", "String", ".", "new", "@s", ".", "scan", "(", "RE_WHITESPACE", ")", "until", "@s", ".", "eos?", "case", "char", "=", "@s", ".", "consume", "when", "')'", "break", "when", "RE_WHITESPACE", "@s", ".", "scan", "(", "RE_WHITESPACE", ")", "if", "@s", ".", "eos?", "||", "@s", ".", "peek", "==", "')'", "@s", ".", "consume", "break", "else", "return", "create_token", "(", ":bad_url", ",", ":value", "=>", "value", "+", "consume_bad_url", ")", "end", "when", "'\"'", ",", "\"'\"", ",", "'('", ",", "RE_NON_PRINTABLE", "# Parse error.", "return", "create_token", "(", ":bad_url", ",", ":error", "=>", "true", ",", ":value", "=>", "value", "+", "consume_bad_url", ")", "when", "'\\\\'", "if", "valid_escape?", "value", "<<", "consume_escaped", "else", "# Parse error.", "return", "create_token", "(", ":bad_url", ",", ":error", "=>", "true", ",", ":value", "=>", "value", "+", "consume_bad_url", ")", "end", "else", "value", "<<", "char", "end", "end", "create_token", "(", ":url", ",", ":value", "=>", "value", ")", "end" ]
Consumes a URL token and returns it. Assumes the original "url(" has already been consumed. 4.3.6. http://dev.w3.org/csswg/css-syntax/#consume-a-url-token
[ "Consumes", "a", "URL", "token", "and", "returns", "it", ".", "Assumes", "the", "original", "url", "(", "has", "already", "been", "consumed", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L533-L576
961
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.convert_string_to_number
def convert_string_to_number(str) matches = RE_NUMBER_STR.match(str) s = matches[:sign] == '-' ? -1 : 1 i = matches[:integer].to_i f = matches[:fractional].to_i d = matches[:fractional] ? matches[:fractional].length : 0 t = matches[:exponent_sign] == '-' ? -1 : 1 e = matches[:exponent].to_i # I know this looks nutty, but it's exactly what's defined in the spec, # and it works. s * (i + f * 10**-d) * 10**(t * e) end
ruby
def convert_string_to_number(str) matches = RE_NUMBER_STR.match(str) s = matches[:sign] == '-' ? -1 : 1 i = matches[:integer].to_i f = matches[:fractional].to_i d = matches[:fractional] ? matches[:fractional].length : 0 t = matches[:exponent_sign] == '-' ? -1 : 1 e = matches[:exponent].to_i # I know this looks nutty, but it's exactly what's defined in the spec, # and it works. s * (i + f * 10**-d) * 10**(t * e) end
[ "def", "convert_string_to_number", "(", "str", ")", "matches", "=", "RE_NUMBER_STR", ".", "match", "(", "str", ")", "s", "=", "matches", "[", ":sign", "]", "==", "'-'", "?", "-", "1", ":", "1", "i", "=", "matches", "[", ":integer", "]", ".", "to_i", "f", "=", "matches", "[", ":fractional", "]", ".", "to_i", "d", "=", "matches", "[", ":fractional", "]", "?", "matches", "[", ":fractional", "]", ".", "length", ":", "0", "t", "=", "matches", "[", ":exponent_sign", "]", "==", "'-'", "?", "-", "1", ":", "1", "e", "=", "matches", "[", ":exponent", "]", ".", "to_i", "# I know this looks nutty, but it's exactly what's defined in the spec,", "# and it works.", "s", "*", "(", "i", "+", "f", "*", "10", "**", "-", "d", ")", "*", "10", "**", "(", "t", "*", "e", ")", "end" ]
Converts a valid CSS number string into a number and returns the number. 4.3.14. http://dev.w3.org/csswg/css-syntax/#convert-a-string-to-a-number
[ "Converts", "a", "valid", "CSS", "number", "string", "into", "a", "number", "and", "returns", "the", "number", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L581-L594
962
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.preprocess
def preprocess(input) input = input.to_s.encode('UTF-8', :invalid => :replace, :undef => :replace) input.gsub!(/(?:\r\n|[\r\f])/, "\n") input.gsub!("\u0000", "\ufffd") input end
ruby
def preprocess(input) input = input.to_s.encode('UTF-8', :invalid => :replace, :undef => :replace) input.gsub!(/(?:\r\n|[\r\f])/, "\n") input.gsub!("\u0000", "\ufffd") input end
[ "def", "preprocess", "(", "input", ")", "input", "=", "input", ".", "to_s", ".", "encode", "(", "'UTF-8'", ",", ":invalid", "=>", ":replace", ",", ":undef", "=>", ":replace", ")", "input", ".", "gsub!", "(", "/", "\\r", "\\n", "\\r", "\\f", "/", ",", "\"\\n\"", ")", "input", ".", "gsub!", "(", "\"\\u0000\"", ",", "\"\\ufffd\"", ")", "input", "end" ]
Preprocesses _input_ to prepare it for the tokenizer. 3.3. http://dev.w3.org/csswg/css-syntax/#input-preprocessing
[ "Preprocesses", "_input_", "to", "prepare", "it", "for", "the", "tokenizer", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L608-L616
963
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.start_identifier?
def start_identifier?(text = nil) text = @s.current + @s.peek(2) if text.nil? case text[0] when '-' nextChar = text[1] !!(nextChar == '-' || nextChar =~ RE_NAME_START || valid_escape?(text[1, 2])) when RE_NAME_START true when '\\' valid_escape?(text[0, 2]) else false end end
ruby
def start_identifier?(text = nil) text = @s.current + @s.peek(2) if text.nil? case text[0] when '-' nextChar = text[1] !!(nextChar == '-' || nextChar =~ RE_NAME_START || valid_escape?(text[1, 2])) when RE_NAME_START true when '\\' valid_escape?(text[0, 2]) else false end end
[ "def", "start_identifier?", "(", "text", "=", "nil", ")", "text", "=", "@s", ".", "current", "+", "@s", ".", "peek", "(", "2", ")", "if", "text", ".", "nil?", "case", "text", "[", "0", "]", "when", "'-'", "nextChar", "=", "text", "[", "1", "]", "!", "!", "(", "nextChar", "==", "'-'", "||", "nextChar", "=~", "RE_NAME_START", "||", "valid_escape?", "(", "text", "[", "1", ",", "2", "]", ")", ")", "when", "RE_NAME_START", "true", "when", "'\\\\'", "valid_escape?", "(", "text", "[", "0", ",", "2", "]", ")", "else", "false", "end", "end" ]
Returns `true` if the given three-character _text_ would start an identifier. If _text_ is `nil`, the current and next two characters in the input stream will be checked, but will not be consumed. 4.3.10. http://dev.w3.org/csswg/css-syntax/#would-start-an-identifier
[ "Returns", "true", "if", "the", "given", "three", "-", "character", "_text_", "would", "start", "an", "identifier", ".", "If", "_text_", "is", "nil", "the", "current", "and", "next", "two", "characters", "in", "the", "input", "stream", "will", "be", "checked", "but", "will", "not", "be", "consumed", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L623-L640
964
rgrove/crass
lib/crass/tokenizer.rb
Crass.Tokenizer.start_number?
def start_number?(text = nil) text = @s.current + @s.peek(2) if text.nil? case text[0] when '+', '-' !!(text[1] =~ RE_DIGIT || (text[1] == '.' && text[2] =~ RE_DIGIT)) when '.' !!(text[1] =~ RE_DIGIT) when RE_DIGIT true else false end end
ruby
def start_number?(text = nil) text = @s.current + @s.peek(2) if text.nil? case text[0] when '+', '-' !!(text[1] =~ RE_DIGIT || (text[1] == '.' && text[2] =~ RE_DIGIT)) when '.' !!(text[1] =~ RE_DIGIT) when RE_DIGIT true else false end end
[ "def", "start_number?", "(", "text", "=", "nil", ")", "text", "=", "@s", ".", "current", "+", "@s", ".", "peek", "(", "2", ")", "if", "text", ".", "nil?", "case", "text", "[", "0", "]", "when", "'+'", ",", "'-'", "!", "!", "(", "text", "[", "1", "]", "=~", "RE_DIGIT", "||", "(", "text", "[", "1", "]", "==", "'.'", "&&", "text", "[", "2", "]", "=~", "RE_DIGIT", ")", ")", "when", "'.'", "!", "!", "(", "text", "[", "1", "]", "=~", "RE_DIGIT", ")", "when", "RE_DIGIT", "true", "else", "false", "end", "end" ]
Returns `true` if the given three-character _text_ would start a number. If _text_ is `nil`, the current and next two characters in the input stream will be checked, but will not be consumed. 4.3.11. http://dev.w3.org/csswg/css-syntax/#starts-with-a-number
[ "Returns", "true", "if", "the", "given", "three", "-", "character", "_text_", "would", "start", "a", "number", ".", "If", "_text_", "is", "nil", "the", "current", "and", "next", "two", "characters", "in", "the", "input", "stream", "will", "be", "checked", "but", "will", "not", "be", "consumed", "." ]
074e56f2a9f10bb873fa8e708ef58a065d4281a2
https://github.com/rgrove/crass/blob/074e56f2a9f10bb873fa8e708ef58a065d4281a2/lib/crass/tokenizer.rb#L647-L663
965
suweller/mongoid-autoinc
lib/autoinc.rb
Mongoid.Autoinc.assign!
def assign!(field) options = self.class.incrementing_fields[field] fail AutoIncrementsError if options[:auto] fail AlreadyAssignedError if send(field).present? increment!(field, options) end
ruby
def assign!(field) options = self.class.incrementing_fields[field] fail AutoIncrementsError if options[:auto] fail AlreadyAssignedError if send(field).present? increment!(field, options) end
[ "def", "assign!", "(", "field", ")", "options", "=", "self", ".", "class", ".", "incrementing_fields", "[", "field", "]", "fail", "AutoIncrementsError", "if", "options", "[", ":auto", "]", "fail", "AlreadyAssignedError", "if", "send", "(", "field", ")", ".", "present?", "increment!", "(", "field", ",", "options", ")", "end" ]
Manually assign the next number to the passed autoinc field. @raise [ Mongoid::Autoinc::AutoIncrementsError ] When `auto: true` is set in the increments call for `field` @raise [ AlreadyAssignedError ] When called more then once. @return [ Fixnum ] The assigned number
[ "Manually", "assign", "the", "next", "number", "to", "the", "passed", "autoinc", "field", "." ]
30cfe694da15ddfa2709249fdfdd5d22b93e63c1
https://github.com/suweller/mongoid-autoinc/blob/30cfe694da15ddfa2709249fdfdd5d22b93e63c1/lib/autoinc.rb#L82-L87
966
suweller/mongoid-autoinc
lib/autoinc.rb
Mongoid.Autoinc.update_auto_increments
def update_auto_increments self.class.incrementing_fields.each do |field, options| increment!(field, options) if options[:auto] end && true end
ruby
def update_auto_increments self.class.incrementing_fields.each do |field, options| increment!(field, options) if options[:auto] end && true end
[ "def", "update_auto_increments", "self", ".", "class", ".", "incrementing_fields", ".", "each", "do", "|", "field", ",", "options", "|", "increment!", "(", "field", ",", "options", ")", "if", "options", "[", ":auto", "]", "end", "&&", "true", "end" ]
Sets autoincrement values for all autoincrement fields. @return [ true ]
[ "Sets", "autoincrement", "values", "for", "all", "autoincrement", "fields", "." ]
30cfe694da15ddfa2709249fdfdd5d22b93e63c1
https://github.com/suweller/mongoid-autoinc/blob/30cfe694da15ddfa2709249fdfdd5d22b93e63c1/lib/autoinc.rb#L92-L96
967
suweller/mongoid-autoinc
lib/autoinc.rb
Mongoid.Autoinc.increment!
def increment!(field, options) options = options.dup model_name = (options.delete(:model_name) || self.class.model_name).to_s options[:scope] = evaluate_scope(options[:scope]) if options[:scope] options[:step] = evaluate_step(options[:step]) if options[:step] write_attribute( field.to_sym, Mongoid::Autoinc::Incrementor.new(model_name, field, options).inc ) end
ruby
def increment!(field, options) options = options.dup model_name = (options.delete(:model_name) || self.class.model_name).to_s options[:scope] = evaluate_scope(options[:scope]) if options[:scope] options[:step] = evaluate_step(options[:step]) if options[:step] write_attribute( field.to_sym, Mongoid::Autoinc::Incrementor.new(model_name, field, options).inc ) end
[ "def", "increment!", "(", "field", ",", "options", ")", "options", "=", "options", ".", "dup", "model_name", "=", "(", "options", ".", "delete", "(", ":model_name", ")", "||", "self", ".", "class", ".", "model_name", ")", ".", "to_s", "options", "[", ":scope", "]", "=", "evaluate_scope", "(", "options", "[", ":scope", "]", ")", "if", "options", "[", ":scope", "]", "options", "[", ":step", "]", "=", "evaluate_step", "(", "options", "[", ":step", "]", ")", "if", "options", "[", ":step", "]", "write_attribute", "(", "field", ".", "to_sym", ",", "Mongoid", "::", "Autoinc", "::", "Incrementor", ".", "new", "(", "model_name", ",", "field", ",", "options", ")", ".", "inc", ")", "end" ]
Set autoincrement value for the passed autoincrement field, using the passed options @param [ Symbol ] field Field to set the autoincrement value for. @param [ Hash ] options Options to pass through to the serializer. @return [ true ] The value of `write_attribute`
[ "Set", "autoincrement", "value", "for", "the", "passed", "autoincrement", "field", "using", "the", "passed", "options" ]
30cfe694da15ddfa2709249fdfdd5d22b93e63c1
https://github.com/suweller/mongoid-autoinc/blob/30cfe694da15ddfa2709249fdfdd5d22b93e63c1/lib/autoinc.rb#L105-L114
968
suweller/mongoid-autoinc
lib/autoinc.rb
Mongoid.Autoinc.evaluate_scope
def evaluate_scope(scope) return send(scope) if scope.is_a? Symbol return instance_exec(&scope) if scope.is_a? Proc fail ArgumentError, 'scope is not a Symbol or a Proc' end
ruby
def evaluate_scope(scope) return send(scope) if scope.is_a? Symbol return instance_exec(&scope) if scope.is_a? Proc fail ArgumentError, 'scope is not a Symbol or a Proc' end
[ "def", "evaluate_scope", "(", "scope", ")", "return", "send", "(", "scope", ")", "if", "scope", ".", "is_a?", "Symbol", "return", "instance_exec", "(", "scope", ")", "if", "scope", ".", "is_a?", "Proc", "fail", "ArgumentError", ",", "'scope is not a Symbol or a Proc'", "end" ]
Asserts the validity of the passed scope @param [ Object ] scope The +Symbol+ or +Proc+ to evaluate @raise [ ArgumentError ] When +scope+ is not a +Symbol+ or +Proc+ @return [ Object ] The scope of the autoincrement call
[ "Asserts", "the", "validity", "of", "the", "passed", "scope" ]
30cfe694da15ddfa2709249fdfdd5d22b93e63c1
https://github.com/suweller/mongoid-autoinc/blob/30cfe694da15ddfa2709249fdfdd5d22b93e63c1/lib/autoinc.rb#L123-L127
969
suweller/mongoid-autoinc
lib/autoinc.rb
Mongoid.Autoinc.evaluate_step
def evaluate_step(step) return step if step.is_a? Integer return evaluate_step_proc(step) if step.is_a? Proc fail ArgumentError, 'step is not an Integer or a Proc' end
ruby
def evaluate_step(step) return step if step.is_a? Integer return evaluate_step_proc(step) if step.is_a? Proc fail ArgumentError, 'step is not an Integer or a Proc' end
[ "def", "evaluate_step", "(", "step", ")", "return", "step", "if", "step", ".", "is_a?", "Integer", "return", "evaluate_step_proc", "(", "step", ")", "if", "step", ".", "is_a?", "Proc", "fail", "ArgumentError", ",", "'step is not an Integer or a Proc'", "end" ]
Returns the number to add to the current increment @param [ Object ] step The +Integer+ to be returned or +Proc+ to be evaluated @raise [ ArgumentError ] When +step+ is not an +Integer+ or +Proc+ @return [ Integer ] The number to add to the current increment
[ "Returns", "the", "number", "to", "add", "to", "the", "current", "increment" ]
30cfe694da15ddfa2709249fdfdd5d22b93e63c1
https://github.com/suweller/mongoid-autoinc/blob/30cfe694da15ddfa2709249fdfdd5d22b93e63c1/lib/autoinc.rb#L137-L141
970
suweller/mongoid-autoinc
lib/autoinc.rb
Mongoid.Autoinc.evaluate_step_proc
def evaluate_step_proc(step_proc) result = instance_exec(&step_proc) return result if result.is_a? Integer fail 'step Proc does not evaluate to an Integer' end
ruby
def evaluate_step_proc(step_proc) result = instance_exec(&step_proc) return result if result.is_a? Integer fail 'step Proc does not evaluate to an Integer' end
[ "def", "evaluate_step_proc", "(", "step_proc", ")", "result", "=", "instance_exec", "(", "step_proc", ")", "return", "result", "if", "result", ".", "is_a?", "Integer", "fail", "'step Proc does not evaluate to an Integer'", "end" ]
Executes a proc and returns its +Integer+ value @param [ Proc ] step_proc The +Proc+ to call @raise [ ArgumentError ] When +step_proc+ does not evaluate to +Integer+ @return [ Integer ] The number to add to the current increment
[ "Executes", "a", "proc", "and", "returns", "its", "+", "Integer", "+", "value" ]
30cfe694da15ddfa2709249fdfdd5d22b93e63c1
https://github.com/suweller/mongoid-autoinc/blob/30cfe694da15ddfa2709249fdfdd5d22b93e63c1/lib/autoinc.rb#L150-L154
971
mbklein/equivalent-xml
lib/equivalent-xml.rb
EquivalentXml.Processor.same_namespace?
def same_namespace?(node_1, node_2) args = [node_1,node_2] # CharacterData nodes shouldn't have namespaces. But in Nokogiri, # they do. And they're invisible. And they get corrupted easily. # So let's wilfully ignore them. And while we're at it, let's # ignore any class that doesn't know it has a namespace. if args.all? { |node| not node.is_namespaced? } or args.any? { |node| node.is_character_data? } return true end href1 = node_1.namespace_uri || '' href2 = node_2.namespace_uri || '' return href1 == href2 end
ruby
def same_namespace?(node_1, node_2) args = [node_1,node_2] # CharacterData nodes shouldn't have namespaces. But in Nokogiri, # they do. And they're invisible. And they get corrupted easily. # So let's wilfully ignore them. And while we're at it, let's # ignore any class that doesn't know it has a namespace. if args.all? { |node| not node.is_namespaced? } or args.any? { |node| node.is_character_data? } return true end href1 = node_1.namespace_uri || '' href2 = node_2.namespace_uri || '' return href1 == href2 end
[ "def", "same_namespace?", "(", "node_1", ",", "node_2", ")", "args", "=", "[", "node_1", ",", "node_2", "]", "# CharacterData nodes shouldn't have namespaces. But in Nokogiri,", "# they do. And they're invisible. And they get corrupted easily.", "# So let's wilfully ignore them. And while we're at it, let's", "# ignore any class that doesn't know it has a namespace.", "if", "args", ".", "all?", "{", "|", "node", "|", "not", "node", ".", "is_namespaced?", "}", "or", "args", ".", "any?", "{", "|", "node", "|", "node", ".", "is_character_data?", "}", "return", "true", "end", "href1", "=", "node_1", ".", "namespace_uri", "||", "''", "href2", "=", "node_2", ".", "namespace_uri", "||", "''", "return", "href1", "==", "href2", "end" ]
Determine if two nodes are in the same effective Namespace @param [Node OR String] node_1 The first node to test @param [Node OR String] node_2 The second node to test
[ "Determine", "if", "two", "nodes", "are", "in", "the", "same", "effective", "Namespace" ]
47de39c006636eaeea2eb153e0a346470e0ec693
https://github.com/mbklein/equivalent-xml/blob/47de39c006636eaeea2eb153e0a346470e0ec693/lib/equivalent-xml.rb#L181-L196
972
phatworx/easy_captcha
lib/easy_captcha/controller_helpers.rb
EasyCaptcha.ControllerHelpers.generate_captcha
def generate_captcha if EasyCaptcha.cache # create cache dir FileUtils.mkdir_p(EasyCaptcha.cache_temp_dir) # select all generated captchas from cache files = Dir.glob(EasyCaptcha.cache_temp_dir + "*.png") unless files.size < EasyCaptcha.cache_size file = File.open(files.at(Kernel.rand(files.size))) session[:captcha] = File.basename(file.path, '.*') if file.mtime < EasyCaptcha.cache_expire.ago File.unlink(file.path) # remove speech version File.unlink(file.path.gsub(/png\z/, "wav")) if File.exists?(file.path.gsub(/png\z/, "wav")) else return file.readlines.join end end generated_code = generate_captcha_code image = Captcha.new(generated_code).image # write captcha for caching File.open(captcha_cache_path(generated_code), 'w') { |f| f.write image } # write speech file if u create a new captcha image EasyCaptcha.espeak.generate(generated_code, speech_captcha_cache_path(generated_code)) if EasyCaptcha.espeak? # return image image else Captcha.new(generate_captcha_code).image end end
ruby
def generate_captcha if EasyCaptcha.cache # create cache dir FileUtils.mkdir_p(EasyCaptcha.cache_temp_dir) # select all generated captchas from cache files = Dir.glob(EasyCaptcha.cache_temp_dir + "*.png") unless files.size < EasyCaptcha.cache_size file = File.open(files.at(Kernel.rand(files.size))) session[:captcha] = File.basename(file.path, '.*') if file.mtime < EasyCaptcha.cache_expire.ago File.unlink(file.path) # remove speech version File.unlink(file.path.gsub(/png\z/, "wav")) if File.exists?(file.path.gsub(/png\z/, "wav")) else return file.readlines.join end end generated_code = generate_captcha_code image = Captcha.new(generated_code).image # write captcha for caching File.open(captcha_cache_path(generated_code), 'w') { |f| f.write image } # write speech file if u create a new captcha image EasyCaptcha.espeak.generate(generated_code, speech_captcha_cache_path(generated_code)) if EasyCaptcha.espeak? # return image image else Captcha.new(generate_captcha_code).image end end
[ "def", "generate_captcha", "if", "EasyCaptcha", ".", "cache", "# create cache dir", "FileUtils", ".", "mkdir_p", "(", "EasyCaptcha", ".", "cache_temp_dir", ")", "# select all generated captchas from cache", "files", "=", "Dir", ".", "glob", "(", "EasyCaptcha", ".", "cache_temp_dir", "+", "\"*.png\"", ")", "unless", "files", ".", "size", "<", "EasyCaptcha", ".", "cache_size", "file", "=", "File", ".", "open", "(", "files", ".", "at", "(", "Kernel", ".", "rand", "(", "files", ".", "size", ")", ")", ")", "session", "[", ":captcha", "]", "=", "File", ".", "basename", "(", "file", ".", "path", ",", "'.*'", ")", "if", "file", ".", "mtime", "<", "EasyCaptcha", ".", "cache_expire", ".", "ago", "File", ".", "unlink", "(", "file", ".", "path", ")", "# remove speech version", "File", ".", "unlink", "(", "file", ".", "path", ".", "gsub", "(", "/", "\\z", "/", ",", "\"wav\"", ")", ")", "if", "File", ".", "exists?", "(", "file", ".", "path", ".", "gsub", "(", "/", "\\z", "/", ",", "\"wav\"", ")", ")", "else", "return", "file", ".", "readlines", ".", "join", "end", "end", "generated_code", "=", "generate_captcha_code", "image", "=", "Captcha", ".", "new", "(", "generated_code", ")", ".", "image", "# write captcha for caching", "File", ".", "open", "(", "captcha_cache_path", "(", "generated_code", ")", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "image", "}", "# write speech file if u create a new captcha image", "EasyCaptcha", ".", "espeak", ".", "generate", "(", "generated_code", ",", "speech_captcha_cache_path", "(", "generated_code", ")", ")", "if", "EasyCaptcha", ".", "espeak?", "# return image", "image", "else", "Captcha", ".", "new", "(", "generate_captcha_code", ")", ".", "image", "end", "end" ]
generate captcha image and return it as blob
[ "generate", "captcha", "image", "and", "return", "it", "as", "blob" ]
d3a0281b00bd8fc67caf15a0380e185809f12252
https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/easy_captcha/controller_helpers.rb#L12-L46
973
phatworx/easy_captcha
lib/easy_captcha/controller_helpers.rb
EasyCaptcha.ControllerHelpers.generate_speech_captcha
def generate_speech_captcha raise RuntimeError, "espeak disabled" unless EasyCaptcha.espeak? if EasyCaptcha.cache File.read(speech_captcha_cache_path(current_captcha_code)) else wav_file = Tempfile.new("#{current_captcha_code}.wav") EasyCaptcha.espeak.generate(current_captcha_code, wav_file.path) File.read(wav_file.path) end end
ruby
def generate_speech_captcha raise RuntimeError, "espeak disabled" unless EasyCaptcha.espeak? if EasyCaptcha.cache File.read(speech_captcha_cache_path(current_captcha_code)) else wav_file = Tempfile.new("#{current_captcha_code}.wav") EasyCaptcha.espeak.generate(current_captcha_code, wav_file.path) File.read(wav_file.path) end end
[ "def", "generate_speech_captcha", "raise", "RuntimeError", ",", "\"espeak disabled\"", "unless", "EasyCaptcha", ".", "espeak?", "if", "EasyCaptcha", ".", "cache", "File", ".", "read", "(", "speech_captcha_cache_path", "(", "current_captcha_code", ")", ")", "else", "wav_file", "=", "Tempfile", ".", "new", "(", "\"#{current_captcha_code}.wav\"", ")", "EasyCaptcha", ".", "espeak", ".", "generate", "(", "current_captcha_code", ",", "wav_file", ".", "path", ")", "File", ".", "read", "(", "wav_file", ".", "path", ")", "end", "end" ]
generate speech by captcha from session
[ "generate", "speech", "by", "captcha", "from", "session" ]
d3a0281b00bd8fc67caf15a0380e185809f12252
https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/easy_captcha/controller_helpers.rb#L49-L58
974
phatworx/easy_captcha
lib/easy_captcha/controller_helpers.rb
EasyCaptcha.ControllerHelpers.generate_captcha_code
def generate_captcha_code session[:captcha] = EasyCaptcha.length.times.collect { EasyCaptcha.chars[rand(EasyCaptcha.chars.size)] }.join end
ruby
def generate_captcha_code session[:captcha] = EasyCaptcha.length.times.collect { EasyCaptcha.chars[rand(EasyCaptcha.chars.size)] }.join end
[ "def", "generate_captcha_code", "session", "[", ":captcha", "]", "=", "EasyCaptcha", ".", "length", ".", "times", ".", "collect", "{", "EasyCaptcha", ".", "chars", "[", "rand", "(", "EasyCaptcha", ".", "chars", ".", "size", ")", "]", "}", ".", "join", "end" ]
generate captcha code, save in session and return
[ "generate", "captcha", "code", "save", "in", "session", "and", "return" ]
d3a0281b00bd8fc67caf15a0380e185809f12252
https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/easy_captcha/controller_helpers.rb#L76-L78
975
phatworx/easy_captcha
lib/easy_captcha/controller_helpers.rb
EasyCaptcha.ControllerHelpers.captcha_valid?
def captcha_valid?(code) return false if session[:captcha].blank? or code.blank? session[:captcha].to_s.upcase == code.to_s.upcase end
ruby
def captcha_valid?(code) return false if session[:captcha].blank? or code.blank? session[:captcha].to_s.upcase == code.to_s.upcase end
[ "def", "captcha_valid?", "(", "code", ")", "return", "false", "if", "session", "[", ":captcha", "]", ".", "blank?", "or", "code", ".", "blank?", "session", "[", ":captcha", "]", ".", "to_s", ".", "upcase", "==", "code", ".", "to_s", ".", "upcase", "end" ]
validate given captcha code and re
[ "validate", "given", "captcha", "code", "and", "re" ]
d3a0281b00bd8fc67caf15a0380e185809f12252
https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/easy_captcha/controller_helpers.rb#L81-L84
976
phatworx/easy_captcha
lib/easy_captcha/view_helpers.rb
EasyCaptcha.ViewHelpers.captcha_tag
def captcha_tag(*args) options = { :alt => 'captcha', :width => EasyCaptcha.image_width, :height => EasyCaptcha.image_height } options.merge! args.extract_options! image_tag(captcha_url(:i => Time.now.to_i), options) end
ruby
def captcha_tag(*args) options = { :alt => 'captcha', :width => EasyCaptcha.image_width, :height => EasyCaptcha.image_height } options.merge! args.extract_options! image_tag(captcha_url(:i => Time.now.to_i), options) end
[ "def", "captcha_tag", "(", "*", "args", ")", "options", "=", "{", ":alt", "=>", "'captcha'", ",", ":width", "=>", "EasyCaptcha", ".", "image_width", ",", ":height", "=>", "EasyCaptcha", ".", "image_height", "}", "options", ".", "merge!", "args", ".", "extract_options!", "image_tag", "(", "captcha_url", "(", ":i", "=>", "Time", ".", "now", ".", "to_i", ")", ",", "options", ")", "end" ]
generate an image_tag for captcha image
[ "generate", "an", "image_tag", "for", "captcha", "image" ]
d3a0281b00bd8fc67caf15a0380e185809f12252
https://github.com/phatworx/easy_captcha/blob/d3a0281b00bd8fc67caf15a0380e185809f12252/lib/easy_captcha/view_helpers.rb#L5-L9
977
kristianmandrup/rails-gallery
lib/rails-gallery/rgallery/photo.rb
RGallery.Photo.source_photos
def source_photos return [] unless sources.kind_of? Array @source_photos ||= sources.map do |source| RGallery::Photo.new source.src, options.merge(:sizing => source.sizing) end end
ruby
def source_photos return [] unless sources.kind_of? Array @source_photos ||= sources.map do |source| RGallery::Photo.new source.src, options.merge(:sizing => source.sizing) end end
[ "def", "source_photos", "return", "[", "]", "unless", "sources", ".", "kind_of?", "Array", "@source_photos", "||=", "sources", ".", "map", "do", "|", "source", "|", "RGallery", "::", "Photo", ".", "new", "source", ".", "src", ",", "options", ".", "merge", "(", ":sizing", "=>", "source", ".", "sizing", ")", "end", "end" ]
A photo can contain a source set of other photos!
[ "A", "photo", "can", "contain", "a", "source", "set", "of", "other", "photos!" ]
cf02ca751ad1e51ed2f4b370baf4e34601c6f897
https://github.com/kristianmandrup/rails-gallery/blob/cf02ca751ad1e51ed2f4b370baf4e34601c6f897/lib/rails-gallery/rgallery/photo.rb#L28-L33
978
kristianmandrup/rails-gallery
lib/rails-gallery/rgallery/photo.rb
RGallery.Photo.sources=
def sources= sources = [] return unless sources.kind_of? Array @sources = sources.map{|source| Hashie::Mash.new source } end
ruby
def sources= sources = [] return unless sources.kind_of? Array @sources = sources.map{|source| Hashie::Mash.new source } end
[ "def", "sources", "=", "sources", "=", "[", "]", "return", "unless", "sources", ".", "kind_of?", "Array", "@sources", "=", "sources", ".", "map", "{", "|", "source", "|", "Hashie", "::", "Mash", ".", "new", "source", "}", "end" ]
make sure that sources are wrapped as Hashies to allow method access
[ "make", "sure", "that", "sources", "are", "wrapped", "as", "Hashies", "to", "allow", "method", "access" ]
cf02ca751ad1e51ed2f4b370baf4e34601c6f897
https://github.com/kristianmandrup/rails-gallery/blob/cf02ca751ad1e51ed2f4b370baf4e34601c6f897/lib/rails-gallery/rgallery/photo.rb#L36-L39
979
tomichj/authenticate
lib/authenticate/configuration.rb
Authenticate.Configuration.modules
def modules modules = @modules.dup # in case the user pushes any on modules << @authentication_strategy modules << :db_password modules << :password_reset modules << :trackable # needs configuration modules << :timeoutable if @timeout_in modules << :lifetimed if @max_session_lifetime modules << :brute_force if @max_consecutive_bad_logins_allowed modules end
ruby
def modules modules = @modules.dup # in case the user pushes any on modules << @authentication_strategy modules << :db_password modules << :password_reset modules << :trackable # needs configuration modules << :timeoutable if @timeout_in modules << :lifetimed if @max_session_lifetime modules << :brute_force if @max_consecutive_bad_logins_allowed modules end
[ "def", "modules", "modules", "=", "@modules", ".", "dup", "# in case the user pushes any on", "modules", "<<", "@authentication_strategy", "modules", "<<", ":db_password", "modules", "<<", ":password_reset", "modules", "<<", ":trackable", "# needs configuration", "modules", "<<", ":timeoutable", "if", "@timeout_in", "modules", "<<", ":lifetimed", "if", "@max_session_lifetime", "modules", "<<", ":brute_force", "if", "@max_consecutive_bad_logins_allowed", "modules", "end" ]
List of symbols naming modules to load.
[ "List", "of", "symbols", "naming", "modules", "to", "load", "." ]
f4cdcbc6e42886394a440182f84ce7fa80cd714a
https://github.com/tomichj/authenticate/blob/f4cdcbc6e42886394a440182f84ce7fa80cd714a/lib/authenticate/configuration.rb#L302-L312
980
tomichj/authenticate
lib/authenticate/session.rb
Authenticate.Session.login
def login(user) @current_user = user @current_user.generate_session_token if user.present? message = catch(:failure) do Authenticate.lifecycle.run_callbacks(:after_set_user, @current_user, self, event: :authentication) Authenticate.lifecycle.run_callbacks(:after_authentication, @current_user, self, event: :authentication) end status = message.present? ? Failure.new(message) : Success.new if status.success? @current_user.save write_cookie if @current_user.session_token else @current_user = nil end yield(status) if block_given? end
ruby
def login(user) @current_user = user @current_user.generate_session_token if user.present? message = catch(:failure) do Authenticate.lifecycle.run_callbacks(:after_set_user, @current_user, self, event: :authentication) Authenticate.lifecycle.run_callbacks(:after_authentication, @current_user, self, event: :authentication) end status = message.present? ? Failure.new(message) : Success.new if status.success? @current_user.save write_cookie if @current_user.session_token else @current_user = nil end yield(status) if block_given? end
[ "def", "login", "(", "user", ")", "@current_user", "=", "user", "@current_user", ".", "generate_session_token", "if", "user", ".", "present?", "message", "=", "catch", "(", ":failure", ")", "do", "Authenticate", ".", "lifecycle", ".", "run_callbacks", "(", ":after_set_user", ",", "@current_user", ",", "self", ",", "event", ":", ":authentication", ")", "Authenticate", ".", "lifecycle", ".", "run_callbacks", "(", ":after_authentication", ",", "@current_user", ",", "self", ",", "event", ":", ":authentication", ")", "end", "status", "=", "message", ".", "present?", "?", "Failure", ".", "new", "(", "message", ")", ":", "Success", ".", "new", "if", "status", ".", "success?", "@current_user", ".", "save", "write_cookie", "if", "@current_user", ".", "session_token", "else", "@current_user", "=", "nil", "end", "yield", "(", "status", ")", "if", "block_given?", "end" ]
Initialize an Authenticate session. The presence of a session does NOT mean the user is logged in; call #logged_in? to determine login status. Finish user login process, *after* the user has been authenticated. The user is authenticated by Authenticate::Controller#authenticate. Called when user creates an account or signs back into the app. Runs all configured callbacks, checking for login failure. If login is successful, @current_user is set and a session token is generated and returned to the client browser. If login fails, the user is NOT logged in. No session token is set, and @current_user will not be set. After callbacks are finished, a {LoginStatus} is yielded to the provided block, if one is provided. @param [User] user login completed for this user @yieldparam [Success,Failure] status result of the sign in operation. @return [User]
[ "Initialize", "an", "Authenticate", "session", "." ]
f4cdcbc6e42886394a440182f84ce7fa80cd714a
https://github.com/tomichj/authenticate/blob/f4cdcbc6e42886394a440182f84ce7fa80cd714a/lib/authenticate/session.rb#L38-L56
981
tomichj/authenticate
lib/authenticate/controller.rb
Authenticate.Controller.require_login
def require_login debug "!!!!!!!!!!!!!!!!!! controller#require_login " # logged_in? #{logged_in?}" unauthorized unless logged_in? message = catch(:failure) do current_user = authenticate_session.current_user Authenticate.lifecycle.run_callbacks(:after_set_user, current_user, authenticate_session, event: :set_user) end unauthorized(message) if message end
ruby
def require_login debug "!!!!!!!!!!!!!!!!!! controller#require_login " # logged_in? #{logged_in?}" unauthorized unless logged_in? message = catch(:failure) do current_user = authenticate_session.current_user Authenticate.lifecycle.run_callbacks(:after_set_user, current_user, authenticate_session, event: :set_user) end unauthorized(message) if message end
[ "def", "require_login", "debug", "\"!!!!!!!!!!!!!!!!!! controller#require_login \"", "# logged_in? #{logged_in?}\"", "unauthorized", "unless", "logged_in?", "message", "=", "catch", "(", ":failure", ")", "do", "current_user", "=", "authenticate_session", ".", "current_user", "Authenticate", ".", "lifecycle", ".", "run_callbacks", "(", ":after_set_user", ",", "current_user", ",", "authenticate_session", ",", "event", ":", ":set_user", ")", "end", "unauthorized", "(", "message", ")", "if", "message", "end" ]
Use this filter as a before_action to control access to controller actions, limiting to logged in users. Placing in application_controller will control access to all controllers. Example: class ApplicationController < ActionController::Base before_action :require_login def index # ... end end
[ "Use", "this", "filter", "as", "a", "before_action", "to", "control", "access", "to", "controller", "actions", "limiting", "to", "logged", "in", "users", "." ]
f4cdcbc6e42886394a440182f84ce7fa80cd714a
https://github.com/tomichj/authenticate/blob/f4cdcbc6e42886394a440182f84ce7fa80cd714a/lib/authenticate/controller.rb#L81-L89
982
tomichj/authenticate
lib/authenticate/controller.rb
Authenticate.Controller.unauthorized
def unauthorized(msg = t('flashes.failure_when_not_signed_in')) authenticate_session.logout respond_to do |format| format.any(:js, :json, :xml) { head :unauthorized } format.any { redirect_unauthorized(msg) } end end
ruby
def unauthorized(msg = t('flashes.failure_when_not_signed_in')) authenticate_session.logout respond_to do |format| format.any(:js, :json, :xml) { head :unauthorized } format.any { redirect_unauthorized(msg) } end end
[ "def", "unauthorized", "(", "msg", "=", "t", "(", "'flashes.failure_when_not_signed_in'", ")", ")", "authenticate_session", ".", "logout", "respond_to", "do", "|", "format", "|", "format", ".", "any", "(", ":js", ",", ":json", ",", ":xml", ")", "{", "head", ":unauthorized", "}", "format", ".", "any", "{", "redirect_unauthorized", "(", "msg", ")", "}", "end", "end" ]
User is not authorized, bounce 'em to sign in
[ "User", "is", "not", "authorized", "bounce", "em", "to", "sign", "in" ]
f4cdcbc6e42886394a440182f84ce7fa80cd714a
https://github.com/tomichj/authenticate/blob/f4cdcbc6e42886394a440182f84ce7fa80cd714a/lib/authenticate/controller.rb#L153-L159
983
yivo/pug-ruby
lib/jade-pug/config.rb
JadePug.Config.method_missing
def method_missing(name, *args, &block) return super if block case args.size when 0 # config.client? if name =~ /\A(\w+)\?\z/ !!(respond_to?($1) ? send($1) : instance_variable_get("@#{ $1 }")) # config.client elsif name =~ /\A(\w+)\z/ instance_variable_get("@#{ $1 }") else super end when 1 # config.client= if name =~ /\A(\w+)=\z/ instance_variable_set("@#{ $1 }", args.first) else super end else super end end
ruby
def method_missing(name, *args, &block) return super if block case args.size when 0 # config.client? if name =~ /\A(\w+)\?\z/ !!(respond_to?($1) ? send($1) : instance_variable_get("@#{ $1 }")) # config.client elsif name =~ /\A(\w+)\z/ instance_variable_get("@#{ $1 }") else super end when 1 # config.client= if name =~ /\A(\w+)=\z/ instance_variable_set("@#{ $1 }", args.first) else super end else super end end
[ "def", "method_missing", "(", "name", ",", "*", "args", ",", "&", "block", ")", "return", "super", "if", "block", "case", "args", ".", "size", "when", "0", "# config.client?", "if", "name", "=~", "/", "\\A", "\\w", "\\?", "\\z", "/", "!", "!", "(", "respond_to?", "(", "$1", ")", "?", "send", "(", "$1", ")", ":", "instance_variable_get", "(", "\"@#{ $1 }\"", ")", ")", "# config.client", "elsif", "name", "=~", "/", "\\A", "\\w", "\\z", "/", "instance_variable_get", "(", "\"@#{ $1 }\"", ")", "else", "super", "end", "when", "1", "# config.client=", "if", "name", "=~", "/", "\\A", "\\w", "\\z", "/", "instance_variable_set", "(", "\"@#{ $1 }\"", ",", "args", ".", "first", ")", "else", "super", "end", "else", "super", "end", "end" ]
Allows to dynamically set config attributes.
[ "Allows", "to", "dynamically", "set", "config", "attributes", "." ]
73489d9c6854e22b8ca648e02a68bb6baa410804
https://github.com/yivo/pug-ruby/blob/73489d9c6854e22b8ca648e02a68bb6baa410804/lib/jade-pug/config.rb#L14-L42
984
yivo/pug-ruby
lib/jade-pug/config.rb
JadePug.Config.to_hash
def to_hash instance_variables.each_with_object({}) do |var, h| h[var[1..-1].to_sym] = instance_variable_get(var) end end
ruby
def to_hash instance_variables.each_with_object({}) do |var, h| h[var[1..-1].to_sym] = instance_variable_get(var) end end
[ "def", "to_hash", "instance_variables", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "var", ",", "h", "|", "h", "[", "var", "[", "1", "..", "-", "1", "]", ".", "to_sym", "]", "=", "instance_variable_get", "(", "var", ")", "end", "end" ]
Transforms config to the hash with all keys symbolized. @return [Hash]
[ "Transforms", "config", "to", "the", "hash", "with", "all", "keys", "symbolized", "." ]
73489d9c6854e22b8ca648e02a68bb6baa410804
https://github.com/yivo/pug-ruby/blob/73489d9c6854e22b8ca648e02a68bb6baa410804/lib/jade-pug/config.rb#L52-L56
985
yivo/pug-ruby
lib/jade-pug/compiler.rb
JadePug.Compiler.prepare_options
def prepare_options(options) options = engine.config.to_hash.merge(options) options.keys.each { |k| options[k.to_s.gsub(/_([a-z])/) { $1.upcase }.to_sym] = options[k] } options.delete_if { |k, v| v.nil? } end
ruby
def prepare_options(options) options = engine.config.to_hash.merge(options) options.keys.each { |k| options[k.to_s.gsub(/_([a-z])/) { $1.upcase }.to_sym] = options[k] } options.delete_if { |k, v| v.nil? } end
[ "def", "prepare_options", "(", "options", ")", "options", "=", "engine", ".", "config", ".", "to_hash", ".", "merge", "(", "options", ")", "options", ".", "keys", ".", "each", "{", "|", "k", "|", "options", "[", "k", ".", "to_s", ".", "gsub", "(", "/", "/", ")", "{", "$1", ".", "upcase", "}", ".", "to_sym", "]", "=", "options", "[", "k", "]", "}", "options", ".", "delete_if", "{", "|", "k", ",", "v", "|", "v", ".", "nil?", "}", "end" ]
Responds for preparing compilation options. The next steps are executed: - is merges options into the engine config - it camelizes and symbolizes every option key - it removes nil values from the options @param options [Hash] @return [Hash]
[ "Responds", "for", "preparing", "compilation", "options", "." ]
73489d9c6854e22b8ca648e02a68bb6baa410804
https://github.com/yivo/pug-ruby/blob/73489d9c6854e22b8ca648e02a68bb6baa410804/lib/jade-pug/compiler.rb#L94-L98
986
yivo/pug-ruby
lib/jade-pug/shipped-compiler.rb
JadePug.ShippedCompiler.read_compiler_source
def read_compiler_source(path) raise engine::CompilerError, "Couldn't read compiler source: #{ path }" unless File.readable?(path) File.read(path) end
ruby
def read_compiler_source(path) raise engine::CompilerError, "Couldn't read compiler source: #{ path }" unless File.readable?(path) File.read(path) end
[ "def", "read_compiler_source", "(", "path", ")", "raise", "engine", "::", "CompilerError", ",", "\"Couldn't read compiler source: #{ path }\"", "unless", "File", ".", "readable?", "(", "path", ")", "File", ".", "read", "(", "path", ")", "end" ]
Reads the compiler source from a file and returns it. @param path [String] @return [String]
[ "Reads", "the", "compiler", "source", "from", "a", "file", "and", "returns", "it", "." ]
73489d9c6854e22b8ca648e02a68bb6baa410804
https://github.com/yivo/pug-ruby/blob/73489d9c6854e22b8ca648e02a68bb6baa410804/lib/jade-pug/shipped-compiler.rb#L54-L57
987
yivo/pug-ruby
lib/jade-pug/system-compiler.rb
JadePug.SystemCompiler.version
def version stdout, exit_status = Open3.capture2 "node", "--eval", \ "console.log(require(#{ JSON.dump(File.join(npm_package_path, "package.json")) }).version)" if exit_status.success? stdout.strip else raise engine::CompilerError, \ %{Failed to get #{ engine.name } version. Perhaps, the problem with Node.js runtime.} end end
ruby
def version stdout, exit_status = Open3.capture2 "node", "--eval", \ "console.log(require(#{ JSON.dump(File.join(npm_package_path, "package.json")) }).version)" if exit_status.success? stdout.strip else raise engine::CompilerError, \ %{Failed to get #{ engine.name } version. Perhaps, the problem with Node.js runtime.} end end
[ "def", "version", "stdout", ",", "exit_status", "=", "Open3", ".", "capture2", "\"node\"", ",", "\"--eval\"", ",", "\"console.log(require(#{ JSON.dump(File.join(npm_package_path, \"package.json\")) }).version)\"", "if", "exit_status", ".", "success?", "stdout", ".", "strip", "else", "raise", "engine", "::", "CompilerError", ",", "%{Failed to get #{ engine.name } version. Perhaps, the problem with Node.js runtime.}", "end", "end" ]
Returns version of engine installed system-wide. @return [String]
[ "Returns", "version", "of", "engine", "installed", "system", "-", "wide", "." ]
73489d9c6854e22b8ca648e02a68bb6baa410804
https://github.com/yivo/pug-ruby/blob/73489d9c6854e22b8ca648e02a68bb6baa410804/lib/jade-pug/system-compiler.rb#L47-L57
988
yivo/pug-ruby
lib/jade-pug/system-compiler.rb
JadePug.SystemCompiler.check_npm_package!
def check_npm_package! exit_status = Open3.capture2("node", "--eval", npm_package_require_snippet)[1] unless exit_status.success? raise engine::CompilerError, \ %{No #{ engine.name } NPM package has been found in your system. } + %{Have you forgotten to "npm install --global #{ npm_package_name }"?} end nil end
ruby
def check_npm_package! exit_status = Open3.capture2("node", "--eval", npm_package_require_snippet)[1] unless exit_status.success? raise engine::CompilerError, \ %{No #{ engine.name } NPM package has been found in your system. } + %{Have you forgotten to "npm install --global #{ npm_package_name }"?} end nil end
[ "def", "check_npm_package!", "exit_status", "=", "Open3", ".", "capture2", "(", "\"node\"", ",", "\"--eval\"", ",", "npm_package_require_snippet", ")", "[", "1", "]", "unless", "exit_status", ".", "success?", "raise", "engine", "::", "CompilerError", ",", "%{No #{ engine.name } NPM package has been found in your system. }", "+", "%{Have you forgotten to \"npm install --global #{ npm_package_name }\"?}", "end", "nil", "end" ]
Checks if engine NPM package is installed. @raise {JadePug::CompilerError} If engine NPM package is not installed. @return [nil]
[ "Checks", "if", "engine", "NPM", "package", "is", "installed", "." ]
73489d9c6854e22b8ca648e02a68bb6baa410804
https://github.com/yivo/pug-ruby/blob/73489d9c6854e22b8ca648e02a68bb6baa410804/lib/jade-pug/system-compiler.rb#L127-L136
989
jmettraux/rufus-lua
lib/rufus/lua/state.rb
Rufus::Lua.StateMixin.loadstring_and_call
def loadstring_and_call(s, bndng, filename, lineno) bottom = stack_top chunk = filename ? "#{filename}:#{lineno}" : 'line' err = Lib.luaL_loadbuffer(@pointer, s, s.bytesize, chunk) fail_if_error('eval:compile', err, bndng, filename, lineno) pcall(bottom, 0, bndng, filename, lineno) # arg_count is set to 0 end
ruby
def loadstring_and_call(s, bndng, filename, lineno) bottom = stack_top chunk = filename ? "#{filename}:#{lineno}" : 'line' err = Lib.luaL_loadbuffer(@pointer, s, s.bytesize, chunk) fail_if_error('eval:compile', err, bndng, filename, lineno) pcall(bottom, 0, bndng, filename, lineno) # arg_count is set to 0 end
[ "def", "loadstring_and_call", "(", "s", ",", "bndng", ",", "filename", ",", "lineno", ")", "bottom", "=", "stack_top", "chunk", "=", "filename", "?", "\"#{filename}:#{lineno}\"", ":", "'line'", "err", "=", "Lib", ".", "luaL_loadbuffer", "(", "@pointer", ",", "s", ",", "s", ".", "bytesize", ",", "chunk", ")", "fail_if_error", "(", "'eval:compile'", ",", "err", ",", "bndng", ",", "filename", ",", "lineno", ")", "pcall", "(", "bottom", ",", "0", ",", "bndng", ",", "filename", ",", "lineno", ")", "# arg_count is set to 0", "end" ]
This method holds the 'eval' mechanism.
[ "This", "method", "holds", "the", "eval", "mechanism", "." ]
7bf215d9222c27895f17bc128b32362caee6dd62
https://github.com/jmettraux/rufus-lua/blob/7bf215d9222c27895f17bc128b32362caee6dd62/lib/rufus/lua/state.rb#L65-L74
990
jmettraux/rufus-lua
lib/rufus/lua/state.rb
Rufus::Lua.StateMixin.stack_to_s
def stack_to_s # warning : don't touch at stack[0] s = (1..stack_top).inject([]) { |a, i| type, tname = stack_type_at(i) val = if type == TSTRING "\"#{stack_fetch(i)}\"" elsif SIMPLE_TYPES.include?(type) stack_fetch(i).to_s elsif type == TTABLE "(# is #{Lib.lua_objlen(@pointer, i)})" else '' end a << "#{i} : #{tname} (#{type}) #{val}" a }.reverse.join("\n") s += "\n" if s.length > 0 s end
ruby
def stack_to_s # warning : don't touch at stack[0] s = (1..stack_top).inject([]) { |a, i| type, tname = stack_type_at(i) val = if type == TSTRING "\"#{stack_fetch(i)}\"" elsif SIMPLE_TYPES.include?(type) stack_fetch(i).to_s elsif type == TTABLE "(# is #{Lib.lua_objlen(@pointer, i)})" else '' end a << "#{i} : #{tname} (#{type}) #{val}" a }.reverse.join("\n") s += "\n" if s.length > 0 s end
[ "def", "stack_to_s", "# warning : don't touch at stack[0]", "s", "=", "(", "1", "..", "stack_top", ")", ".", "inject", "(", "[", "]", ")", "{", "|", "a", ",", "i", "|", "type", ",", "tname", "=", "stack_type_at", "(", "i", ")", "val", "=", "if", "type", "==", "TSTRING", "\"\\\"#{stack_fetch(i)}\\\"\"", "elsif", "SIMPLE_TYPES", ".", "include?", "(", "type", ")", "stack_fetch", "(", "i", ")", ".", "to_s", "elsif", "type", "==", "TTABLE", "\"(# is #{Lib.lua_objlen(@pointer, i)})\"", "else", "''", "end", "a", "<<", "\"#{i} : #{tname} (#{type}) #{val}\"", "a", "}", ".", "reverse", ".", "join", "(", "\"\\n\"", ")", "s", "+=", "\"\\n\"", "if", "s", ".", "length", ">", "0", "s", "end" ]
Returns a string representation of the state's stack.
[ "Returns", "a", "string", "representation", "of", "the", "state", "s", "stack", "." ]
7bf215d9222c27895f17bc128b32362caee6dd62
https://github.com/jmettraux/rufus-lua/blob/7bf215d9222c27895f17bc128b32362caee6dd62/lib/rufus/lua/state.rb#L78-L104
991
jmettraux/rufus-lua
lib/rufus/lua/state.rb
Rufus::Lua.StateMixin.stack_push
def stack_push(o) return stack_push(o.to_lua) if o.respond_to?(:to_lua) case o when NilClass then Lib.lua_pushnil(@pointer) when TrueClass then Lib.lua_pushboolean(@pointer, 1) when FalseClass then Lib.lua_pushboolean(@pointer, 0) when Integer then Lib.lua_pushinteger(@pointer, o) when Float then Lib.lua_pushnumber(@pointer, o) when String then Lib.lua_pushlstring(@pointer, o, o.bytesize) when Symbol then Lib.lua_pushlstring(@pointer, o.to_s, o.to_s.bytesize) when Hash then stack_push_hash(o) when Array then stack_push_array(o) else raise( ArgumentError.new( "don't know how to pass Ruby instance of #{o.class} to Lua")) end end
ruby
def stack_push(o) return stack_push(o.to_lua) if o.respond_to?(:to_lua) case o when NilClass then Lib.lua_pushnil(@pointer) when TrueClass then Lib.lua_pushboolean(@pointer, 1) when FalseClass then Lib.lua_pushboolean(@pointer, 0) when Integer then Lib.lua_pushinteger(@pointer, o) when Float then Lib.lua_pushnumber(@pointer, o) when String then Lib.lua_pushlstring(@pointer, o, o.bytesize) when Symbol then Lib.lua_pushlstring(@pointer, o.to_s, o.to_s.bytesize) when Hash then stack_push_hash(o) when Array then stack_push_array(o) else raise( ArgumentError.new( "don't know how to pass Ruby instance of #{o.class} to Lua")) end end
[ "def", "stack_push", "(", "o", ")", "return", "stack_push", "(", "o", ".", "to_lua", ")", "if", "o", ".", "respond_to?", "(", ":to_lua", ")", "case", "o", "when", "NilClass", "then", "Lib", ".", "lua_pushnil", "(", "@pointer", ")", "when", "TrueClass", "then", "Lib", ".", "lua_pushboolean", "(", "@pointer", ",", "1", ")", "when", "FalseClass", "then", "Lib", ".", "lua_pushboolean", "(", "@pointer", ",", "0", ")", "when", "Integer", "then", "Lib", ".", "lua_pushinteger", "(", "@pointer", ",", "o", ")", "when", "Float", "then", "Lib", ".", "lua_pushnumber", "(", "@pointer", ",", "o", ")", "when", "String", "then", "Lib", ".", "lua_pushlstring", "(", "@pointer", ",", "o", ",", "o", ".", "bytesize", ")", "when", "Symbol", "then", "Lib", ".", "lua_pushlstring", "(", "@pointer", ",", "o", ".", "to_s", ",", "o", ".", "to_s", ".", "bytesize", ")", "when", "Hash", "then", "stack_push_hash", "(", "o", ")", "when", "Array", "then", "stack_push_array", "(", "o", ")", "else", "raise", "(", "ArgumentError", ".", "new", "(", "\"don't know how to pass Ruby instance of #{o.class} to Lua\"", ")", ")", "end", "end" ]
Given a Ruby instance, will attempt to push it on the Lua stack.
[ "Given", "a", "Ruby", "instance", "will", "attempt", "to", "push", "it", "on", "the", "Lua", "stack", "." ]
7bf215d9222c27895f17bc128b32362caee6dd62
https://github.com/jmettraux/rufus-lua/blob/7bf215d9222c27895f17bc128b32362caee6dd62/lib/rufus/lua/state.rb#L190-L214
992
jmettraux/rufus-lua
lib/rufus/lua/state.rb
Rufus::Lua.StateMixin.stack_push_hash
def stack_push_hash(h) Lib.lua_createtable(@pointer, 0, h.size) # since we already know the size of the table... h.each do |k, v| stack_push(k) stack_push(v) Lib.lua_settable(@pointer, -3) end end
ruby
def stack_push_hash(h) Lib.lua_createtable(@pointer, 0, h.size) # since we already know the size of the table... h.each do |k, v| stack_push(k) stack_push(v) Lib.lua_settable(@pointer, -3) end end
[ "def", "stack_push_hash", "(", "h", ")", "Lib", ".", "lua_createtable", "(", "@pointer", ",", "0", ",", "h", ".", "size", ")", "# since we already know the size of the table...", "h", ".", "each", "do", "|", "k", ",", "v", "|", "stack_push", "(", "k", ")", "stack_push", "(", "v", ")", "Lib", ".", "lua_settable", "(", "@pointer", ",", "-", "3", ")", "end", "end" ]
Pushes a hash on top of the Lua stack.
[ "Pushes", "a", "hash", "on", "top", "of", "the", "Lua", "stack", "." ]
7bf215d9222c27895f17bc128b32362caee6dd62
https://github.com/jmettraux/rufus-lua/blob/7bf215d9222c27895f17bc128b32362caee6dd62/lib/rufus/lua/state.rb#L218-L228
993
jmettraux/rufus-lua
lib/rufus/lua/state.rb
Rufus::Lua.StateMixin.stack_push_array
def stack_push_array(a) Lib.lua_createtable(@pointer, a.size, 0) # since we already know the size of the table... a.each_with_index do |e, i| stack_push(i + 1) stack_push(e) Lib.lua_settable(@pointer, -3) end end
ruby
def stack_push_array(a) Lib.lua_createtable(@pointer, a.size, 0) # since we already know the size of the table... a.each_with_index do |e, i| stack_push(i + 1) stack_push(e) Lib.lua_settable(@pointer, -3) end end
[ "def", "stack_push_array", "(", "a", ")", "Lib", ".", "lua_createtable", "(", "@pointer", ",", "a", ".", "size", ",", "0", ")", "# since we already know the size of the table...", "a", ".", "each_with_index", "do", "|", "e", ",", "i", "|", "stack_push", "(", "i", "+", "1", ")", "stack_push", "(", "e", ")", "Lib", ".", "lua_settable", "(", "@pointer", ",", "-", "3", ")", "end", "end" ]
Pushes an array on top of the Lua stack.
[ "Pushes", "an", "array", "on", "top", "of", "the", "Lua", "stack", "." ]
7bf215d9222c27895f17bc128b32362caee6dd62
https://github.com/jmettraux/rufus-lua/blob/7bf215d9222c27895f17bc128b32362caee6dd62/lib/rufus/lua/state.rb#L232-L242
994
bdurand/seamless_database_pool
lib/seamless_database_pool/controller_filter.rb
SeamlessDatabasePool.ControllerFilter.set_read_only_connection_for_block
def set_read_only_connection_for_block(action) read_pool_method = nil if session read_pool_method = session[:next_request_db_connection] session.delete(:next_request_db_connection) if session[:next_request_db_connection] end read_pool_method ||= seamless_database_pool_options[action.to_sym] || seamless_database_pool_options[:all] if read_pool_method SeamlessDatabasePool.set_read_only_connection_type(read_pool_method) do yield end else yield end end
ruby
def set_read_only_connection_for_block(action) read_pool_method = nil if session read_pool_method = session[:next_request_db_connection] session.delete(:next_request_db_connection) if session[:next_request_db_connection] end read_pool_method ||= seamless_database_pool_options[action.to_sym] || seamless_database_pool_options[:all] if read_pool_method SeamlessDatabasePool.set_read_only_connection_type(read_pool_method) do yield end else yield end end
[ "def", "set_read_only_connection_for_block", "(", "action", ")", "read_pool_method", "=", "nil", "if", "session", "read_pool_method", "=", "session", "[", ":next_request_db_connection", "]", "session", ".", "delete", "(", ":next_request_db_connection", ")", "if", "session", "[", ":next_request_db_connection", "]", "end", "read_pool_method", "||=", "seamless_database_pool_options", "[", "action", ".", "to_sym", "]", "||", "seamless_database_pool_options", "[", ":all", "]", "if", "read_pool_method", "SeamlessDatabasePool", ".", "set_read_only_connection_type", "(", "read_pool_method", ")", "do", "yield", "end", "else", "yield", "end", "end" ]
Set the read only connection for a block. Used to set the connection for a controller action.
[ "Set", "the", "read", "only", "connection", "for", "a", "block", ".", "Used", "to", "set", "the", "connection", "for", "a", "controller", "action", "." ]
529c1d49b2c6029de7444830bce72917de79ebff
https://github.com/bdurand/seamless_database_pool/blob/529c1d49b2c6029de7444830bce72917de79ebff/lib/seamless_database_pool/controller_filter.rb#L72-L87
995
jmettraux/rufus-lua
lib/rufus/lua/objects.rb
Rufus::Lua.Function.call
def call(*args) bottom = stack_top load_onto_stack # load function on stack args.each { |arg| stack_push(arg) } # push arguments on stack pcall(bottom, args.length, nil, nil, nil) end
ruby
def call(*args) bottom = stack_top load_onto_stack # load function on stack args.each { |arg| stack_push(arg) } # push arguments on stack pcall(bottom, args.length, nil, nil, nil) end
[ "def", "call", "(", "*", "args", ")", "bottom", "=", "stack_top", "load_onto_stack", "# load function on stack", "args", ".", "each", "{", "|", "arg", "|", "stack_push", "(", "arg", ")", "}", "# push arguments on stack", "pcall", "(", "bottom", ",", "args", ".", "length", ",", "nil", ",", "nil", ",", "nil", ")", "end" ]
Calls the Lua function.
[ "Calls", "the", "Lua", "function", "." ]
7bf215d9222c27895f17bc128b32362caee6dd62
https://github.com/jmettraux/rufus-lua/blob/7bf215d9222c27895f17bc128b32362caee6dd62/lib/rufus/lua/objects.rb#L67-L78
996
jmettraux/rufus-lua
lib/rufus/lua/objects.rb
Rufus::Lua.Coroutine.resume
def resume(*args) bottom = stack_top fetch_library_method('coroutine.resume').load_onto_stack load_onto_stack args.each { |arg| stack_push(arg) } pcall(bottom, args.length + 1, nil, nil, nil) end
ruby
def resume(*args) bottom = stack_top fetch_library_method('coroutine.resume').load_onto_stack load_onto_stack args.each { |arg| stack_push(arg) } pcall(bottom, args.length + 1, nil, nil, nil) end
[ "def", "resume", "(", "*", "args", ")", "bottom", "=", "stack_top", "fetch_library_method", "(", "'coroutine.resume'", ")", ".", "load_onto_stack", "load_onto_stack", "args", ".", "each", "{", "|", "arg", "|", "stack_push", "(", "arg", ")", "}", "pcall", "(", "bottom", ",", "args", ".", "length", "+", "1", ",", "nil", ",", "nil", ",", "nil", ")", "end" ]
Resumes the coroutine
[ "Resumes", "the", "coroutine" ]
7bf215d9222c27895f17bc128b32362caee6dd62
https://github.com/jmettraux/rufus-lua/blob/7bf215d9222c27895f17bc128b32362caee6dd62/lib/rufus/lua/objects.rb#L88-L98
997
jmettraux/rufus-lua
lib/rufus/lua/objects.rb
Rufus::Lua.Table.[]=
def []=(k, v) load_onto_stack stack_push(k) stack_push(v) Lib.lua_settable(@pointer, -3) v end
ruby
def []=(k, v) load_onto_stack stack_push(k) stack_push(v) Lib.lua_settable(@pointer, -3) v end
[ "def", "[]=", "(", "k", ",", "v", ")", "load_onto_stack", "stack_push", "(", "k", ")", "stack_push", "(", "v", ")", "Lib", ".", "lua_settable", "(", "@pointer", ",", "-", "3", ")", "v", "end" ]
Sets a value in the table TODO : have something for adding in the array part...
[ "Sets", "a", "value", "in", "the", "table" ]
7bf215d9222c27895f17bc128b32362caee6dd62
https://github.com/jmettraux/rufus-lua/blob/7bf215d9222c27895f17bc128b32362caee6dd62/lib/rufus/lua/objects.rb#L166-L175
998
jmettraux/rufus-lua
lib/rufus/lua/objects.rb
Rufus::Lua.Table.to_h
def to_h load_onto_stack table_pos = stack_top Lib.lua_pushnil(@pointer) h = {} while Lib.lua_next(@pointer, table_pos) != 0 do value = stack_fetch(-1) value.load_onto_stack if value.is_a?(Ref) key = stack_fetch(-2) key.load_onto_stack if key.is_a?(Ref) stack_unstack # leave key on top h[key] = value end h end
ruby
def to_h load_onto_stack table_pos = stack_top Lib.lua_pushnil(@pointer) h = {} while Lib.lua_next(@pointer, table_pos) != 0 do value = stack_fetch(-1) value.load_onto_stack if value.is_a?(Ref) key = stack_fetch(-2) key.load_onto_stack if key.is_a?(Ref) stack_unstack # leave key on top h[key] = value end h end
[ "def", "to_h", "load_onto_stack", "table_pos", "=", "stack_top", "Lib", ".", "lua_pushnil", "(", "@pointer", ")", "h", "=", "{", "}", "while", "Lib", ".", "lua_next", "(", "@pointer", ",", "table_pos", ")", "!=", "0", "do", "value", "=", "stack_fetch", "(", "-", "1", ")", "value", ".", "load_onto_stack", "if", "value", ".", "is_a?", "(", "Ref", ")", "key", "=", "stack_fetch", "(", "-", "2", ")", "key", ".", "load_onto_stack", "if", "key", ".", "is_a?", "(", "Ref", ")", "stack_unstack", "# leave key on top", "h", "[", "key", "]", "=", "value", "end", "h", "end" ]
Returns a Ruby Hash instance representing this Lua table.
[ "Returns", "a", "Ruby", "Hash", "instance", "representing", "this", "Lua", "table", "." ]
7bf215d9222c27895f17bc128b32362caee6dd62
https://github.com/jmettraux/rufus-lua/blob/7bf215d9222c27895f17bc128b32362caee6dd62/lib/rufus/lua/objects.rb#L199-L223
999
jmettraux/rufus-lua
lib/rufus/lua/objects.rb
Rufus::Lua.Table.to_a
def to_a(pure=true) h = self.to_h pure && h.keys.find { |k| not [ Float ].include?(k.class) } && fail('cannot turn hash into array, some keys are not numbers') a_keys = (1..objlen).to_a.collect { |k| k.to_f } keys = a_keys + (h.keys - a_keys) keys.inject([]) { |a, k| a << (a_keys.include?(k) ? h[k] : [ k, h[k] ]) a } end
ruby
def to_a(pure=true) h = self.to_h pure && h.keys.find { |k| not [ Float ].include?(k.class) } && fail('cannot turn hash into array, some keys are not numbers') a_keys = (1..objlen).to_a.collect { |k| k.to_f } keys = a_keys + (h.keys - a_keys) keys.inject([]) { |a, k| a << (a_keys.include?(k) ? h[k] : [ k, h[k] ]) a } end
[ "def", "to_a", "(", "pure", "=", "true", ")", "h", "=", "self", ".", "to_h", "pure", "&&", "h", ".", "keys", ".", "find", "{", "|", "k", "|", "not", "[", "Float", "]", ".", "include?", "(", "k", ".", "class", ")", "}", "&&", "fail", "(", "'cannot turn hash into array, some keys are not numbers'", ")", "a_keys", "=", "(", "1", "..", "objlen", ")", ".", "to_a", ".", "collect", "{", "|", "k", "|", "k", ".", "to_f", "}", "keys", "=", "a_keys", "+", "(", "h", ".", "keys", "-", "a_keys", ")", "keys", ".", "inject", "(", "[", "]", ")", "{", "|", "a", ",", "k", "|", "a", "<<", "(", "a_keys", ".", "include?", "(", "k", ")", "?", "h", "[", "k", "]", ":", "[", "k", ",", "h", "[", "k", "]", "]", ")", "a", "}", "end" ]
Returns a Ruby Array instance representing this Lua table. Will raise an error if the 'rendering' is not possible. s = Rufus::Lua::State.new @s.eval("return { a = 'A', b = 'B', c = 3 }").to_a # => error ! @s.eval("return { 1, 2 }").to_a # => [ 1.0, 2.0 ] @s.eval("return {}").to_a # => [] @s.eval("return { 1, 2, car = 'benz' }").to_a # => error ! == to_a(false) Setting the optional argument 'pure' to false will manage any table : s = Rufus::Lua::State.new @s.eval("return { a = 'A', b = 'B', c = 3 }").to_a(false) # => [["a", "A"], ["b", "B"], ["c", 3.0]] @s.eval("return { 1, 2 }").to_a(false) # => [1.0, 2.0] @s.eval("return {}").to_a(false) # => [] @s.eval("return { 1, 2, car = 'benz' }").to_a(false) # => [1.0, 2.0, ["car", "benz"]]
[ "Returns", "a", "Ruby", "Array", "instance", "representing", "this", "Lua", "table", "." ]
7bf215d9222c27895f17bc128b32362caee6dd62
https://github.com/jmettraux/rufus-lua/blob/7bf215d9222c27895f17bc128b32362caee6dd62/lib/rufus/lua/objects.rb#L261-L275