Permalink
Browse files

init commit

  • Loading branch information...
0 parents commit 9ff3bb199c1b116dbce089d3e37a926ac7f7f38c @siuying committed Feb 12, 2011
Showing with 516 additions and 0 deletions.
  1. +4 −0 .document
  2. +44 −0 .gitignore
  3. +16 −0 Gemfile
  4. +20 −0 LICENSE.txt
  5. +102 −0 README.md
  6. +48 −0 Rakefile
  7. +1 −0 VERSION
  8. +5 −0 bin/rquery
  9. +138 −0 lib/rquery.rb
  10. +57 −0 rquery.gemspec
  11. +65 −0 spec/rquery/rquery_spec.rb
  12. +3 −0 spec/spec.opts
  13. +13 −0 spec/spec_helper.rb
@@ -0,0 +1,4 @@
+README.md
+lib/*.rb
+bin/*
+LICENSE
@@ -0,0 +1,44 @@
+# rcov generated
+coverage
+
+# rdoc generated
+rdoc
+
+# yard generated
+doc
+.yardoc
+
+# bundler
+.bundle
+
+# jeweler generated
+pkg
+
+# Have editor/IDE/OS specific files you need to ignore? Consider using a global gitignore:
+#
+# * Create a file at ~/.gitignore
+# * Include files you want ignored
+# * Run: git config --global core.excludesfile ~/.gitignore
+#
+# After doing this, these files will be ignored in all your git projects,
+# saving you from having to 'pollute' every project you touch with them
+#
+# Not sure what to needs to be ignored for particular editors/OSes? Here's some ideas to get you started. (Remember, remove the leading # of the line)
+#
+# For MacOS:
+#
+.DS_Store
+#
+# For TextMate
+#*.tmproj
+#tmtags
+#
+# For emacs:
+#*~
+#\#*
+#.\#*
+#
+# For vim:
+#*.swp
+
+Gemfile.*
@@ -0,0 +1,16 @@
+source 'http://rubygems.org'
+
+group :default do
+ gem 'nokogiri'
+end
+
+group :development do
+ gem 'rake'
+ gem 'json'
+ gem 'jeweler'
+end
+
+group :test do
+ gem 'rspec', '~> 2.0'
+end
+
@@ -0,0 +1,20 @@
+Copyright (c) 2011 Francis Chong
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,102 @@
+# RQuery
+
+ jQuery for command line and ruby. It make extract simple data fun and easy.
+
+ It use Nokogiri for CSS extraction. Inspired by node [Query](https://github.com/visionmedia/query)
+
+## Installation
+
+ $ gem install rquery
+
+
+## Ruby Examples
+
+ Extract an attribute from a webpage:
+
+ require 'open-uri'
+ require 'rquery'
+
+ RQuery::Query.query(open("http://twitter.com"), "a#logo img", "attr", "alt")
+ => "Twitter"
+
+ Extract a form input value :
+
+ require 'rquery'
+
+ RQuery::Query.query('<input type="text" value="tj@vision-media.ca"/>', "input", "val")
+ => "tj@vision-media.ca"
+
+## Command Line Examples
+
+ Twitter logo alt text:
+
+ $ curl http://twitter.com | query 'a#logo img' attr alt
+ Twitter
+
+ Alternately, since the output is simply more html, we can achieve this same result via pipes:
+
+ $ curl http://twitter.com | query 'a#logo' | query img attr alt
+ Twitter
+
+ Check if a class is present:
+
+ $ curl http://twitter.com | query .article '#timeline' hasClass statuses
+ true
+
+ $ echo $?
+ 0
+
+ Exit status for bools:
+
+ $ echo '<div class="foo bar"></div>' | ./index.js div hasClass baz
+ false
+
+ $ echo $?
+ 1
+
+ Grab width or height attributes:
+
+ $ echo '<div class="user" width="300"></div>' | query div.user width
+ 300
+
+ Output element text:
+
+ $ echo '<p>very <em>slick</em></p>' | query p text
+ very slick
+
+ Values:
+
+ $ echo '<input type="text" value="tj@vision-media.ca"/>' | query input val
+ tj@vision-media.ca
+
+ Get second li's text:
+
+ $ echo $list | query ul li get 1 text
+ two
+
+ Get third li's text using `next`:
+
+ $ echo $list | query ul li get 1 next text
+ three
+
+ Get length:
+
+ $ echo '<ul><li></li><li></li></ul>' | query li length
+ 2
+
+
+## Contributing to RQuery
+
+* Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet
+* Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it
+* Fork the project
+* Start a feature/bugfix branch
+* Commit and push until you are happy with your contribution
+* Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
+* Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.
+
+## Copyright
+
+Copyright (c) 2011 Francis Chong. See LICENSE.txt for
+further details.
+
@@ -0,0 +1,48 @@
+require 'rubygems'
+require 'bundler'
+begin
+ Bundler.setup(:default, :development, :test)
+rescue Bundler::BundlerError => e
+ $stderr.puts e.message
+ $stderr.puts "Run `bundle install` to install missing gems"
+ exit e.status_code
+end
+require 'rake'
+
+require 'jeweler'
+Jeweler::Tasks.new do |gem|
+ # gem is a Gem::Specification... see http://docs.rubygems.org/read/chapter/20 for more options
+ gem.name = "rquery"
+ gem.files = ["lib/*.rb", "lib/**/*.rb", "bin/*"]
+ gem.executables = ['rquery']
+ gem.homepage = "http://github.com/siuying/rquery"
+ gem.license = "MIT"
+ gem.summary = %Q{Simple jQuery style method to extract HTML}
+ gem.description = %Q{RQuery is a simple jQuery style method to extract HTML}
+ gem.email = "francis@ignition.hk"
+ gem.authors = ["Francis Chong"]
+
+ # Include your dependencies below. Runtime dependencies are required when using your gem,
+ # and development dependencies are only needed for development (ie running rake tasks, tests, etc)
+ gem.add_runtime_dependency 'nokogiri', '> 1.4.0'
+ gem.add_development_dependency 'rspec', '> 1.2.3'
+end
+Jeweler::RubygemsDotOrgTasks.new
+
+require 'rspec/core/rake_task'
+RSpec::Core::RakeTask.new do |spec|
+ # spec.libs << 'lib' << 'spec'
+ spec.pattern = 'spec/**/*_spec.rb'
+end
+
+task :default => :test
+
+require 'rake/rdoctask'
+Rake::RDocTask.new do |rdoc|
+ version = File.exist?('VERSION') ? File.read('VERSION') : ""
+
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = "helloworld #{version}"
+ rdoc.rdoc_files.include('README*')
+ rdoc.rdoc_files.include('./lib/*.rb')
+end
@@ -0,0 +1 @@
+0.1.0
@@ -0,0 +1,5 @@
+require 'rquery'
+
+html = STDIN.read
+puts RQuery::Query.query(html, *ARGV)
+
@@ -0,0 +1,138 @@
+require 'nokogiri'
+
+module RQuery
+ class QueryError < StandardError
+ attr_accessor :context, :command_name, :command_type, :param, :message
+ def initialize(context, name, type, param, msg)
+ @context = context
+ @command_name = name
+ @command_type = type
+ @param = param
+ @message = msg
+ end
+
+ def to_s
+ "#{command_type}:#{command_name} param=#{param}, message=#{message}"
+ end
+ end
+
+ class Query
+ # supported commands
+ COMMANDS = {
+ :to_html => {:type => 'method'},
+ :inner_html => {:type => 'method'},
+ :text => {:type => 'method'},
+ :size => {:type => 'method'},
+
+ :width => {:type => 'attribute'},
+ :height => {:type => 'attribute'},
+ :value => {:type => 'attribute'},
+ :class => {:type => 'attribute'},
+
+ :first => {:type => 'traverse'},
+ :last => {:type => 'traverse'},
+ :parent => {:type => 'traverse'},
+ :next_sibling => {:type => 'traverse'},
+ :previous_sibling => {:type => 'traverse'},
+ :at => {:type => 'traverse', :arity => 1},
+
+ :attr => {:type => 'proc',
+ :arity => 1,
+ :proc => Proc.new {|context, param, query|
+ context.attr(param).to_s rescue ""
+ }
+ },
+ :hasClass => {:type => 'proc',
+ :arity => 1,
+ :proc => Proc.new {|context, param, query|
+ if context.is_a?(Nokogiri::XML::Element)
+ !!context["class"].split(" ").find{|x| x == param} rescue false
+ elsif context.is_a?(Nokogiri::XML::NodeSet)
+ !!context.first["class"].split(" ").find{|x| x == param} rescue false
+ else
+ raise QueryError.new(context, name, type, param, "Cannot get hasClass from #{context.class}")
+ end
+ }
+ }
+ }
+
+ ALIAS = {
+ :html => :to_html,
+ :len => :length,
+ :count => :size,
+ :get => :at,
+ :"has-class" => :hasClass,
+ :val => :value
+ }
+
+ def self.query(html, *query)
+ doc = Nokogiri::HTML(html)
+ ctx = doc.search(query.shift)
+
+ while method = query.shift
+ command = COMMANDS[method.to_sym] || COMMANDS[ALIAS[method.to_sym]] || COMMANDS[:to_html]
+ param = query.length > 0 ? (command[:arity] ? query.shift : nil) : nil
+ ctx = handle_command(ctx, ALIAS[method.to_sym] || method.to_sym, command[:type], param, query)
+ end
+
+ if ctx.is_a?(Nokogiri::XML::Element) || ctx.is_a?(Nokogiri::XML::NodeSet)
+ ctx = ctx.to_html
+ else
+ ctx
+ end
+ end
+
+ private
+ def self.handle_command(context, name, type, param=nil, query=nil)
+ case type
+ when 'method'
+ if context.is_a?(Nokogiri::XML::Element) || context.is_a?(Nokogiri::XML::NodeSet)
+ if param
+ context.send(name, param)
+ else
+ context.send(name)
+ end
+
+ elsif context.nil?
+ nil
+
+ else
+ raise QueryError.new(context, name, type, param, "Cannot apply #{name} to #{context.class}")
+ end
+
+ when 'attribute'
+ if context.is_a?(Nokogiri::XML::Element)
+ context[name]
+ elsif context.is_a?(Nokogiri::XML::NodeSet)
+ context.first[name]
+ else
+ raise QueryError.new(context, name, type, param, "Cannot get attr #{name} from #{context.class}")
+ end
+
+ when 'traverse'
+ if name == :at
+ if param.nil?
+ raise QueryError.new(context, name, type, param, "missing at parameter")
+ end
+ context[param.to_i]
+ else
+ if context.is_a?(Nokogiri::XML::Element) || context.is_a?(Nokogiri::XML::NodeSet)
+ if param
+ context.send(name, param)
+ else
+ context.send(name)
+ end
+ else
+ raise QueryError.new(context, name, type, param, "Cannot tranverse #{context.class}")
+ end
+ end
+
+ when 'proc'
+ COMMANDS[name][:proc].call(context, param, query)
+
+ else
+ raise QueryError.new(context, name, type, param, 'Unexpected type: #{type}')
+ end
+ end
+ end
+end
Oops, something went wrong.

0 comments on commit 9ff3bb1

Please sign in to comment.