facets-2.9.3/0000755000004100000410000000000011714455227013032 5ustar www-datawww-datafacets-2.9.3/RUBY.txt0000644000004100000410000004362211714455227014363 0ustar www-datawww-data Ruby Facets Copyright (c) 2005,2010 Thomas Sawyer THE RUBY LICENSE (http://www.ruby-lang.org/en/LICENSE.txt) You may redistribute this software and/or modify it under either the terms of the GPL (see below), or the conditions below: 1. You may make and give away verbatim copies of the source form of the software without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may modify your copy of the software in any way, provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or by allowing the author to include your modifications in the software. b) use the modified software only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided. d) make other distribution arrangements with the author. 3. You may distribute the software in object code or executable form, provided that you do at least ONE of the following: a) distribute the executables and library files of the software, together with instructions (in the manual page or equivalent) on where to get the original distribution. b) accompany the distribution with the machine-readable source of the software. c) give non-standard executables non-standard names, with instructions on where to get the original software distribution. d) make other distribution arrangements with the author. 4. You may modify and include the part of the software into any other software (possibly commercial). But some files in the distribution are not written by the author, so that they are not under these terms. For the list of those files and their copying conditions, see the file LEGAL. 5. The scripts and library files supplied as input to or produced as output from the software do not automatically fall under the copyright of the software, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this software. 6. THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ---------------------------------------------------------------------------- GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS facets-2.9.3/test/0000755000004100000410000000000011714455226014010 5ustar www-datawww-datafacets-2.9.3/test/core/0000755000004100000410000000000011714455226014740 5ustar www-datawww-datafacets-2.9.3/test/core/comparable/0000755000004100000410000000000011714455226017045 5ustar www-datawww-datafacets-2.9.3/test/core/comparable/test_bound.rb0000644000004100000410000000117611714455226021545 0ustar www-datawww-datacovers 'facets/comparable/bound' test_case Comparable do method :bound do test 'single argument' do 3.bound(4).assert == 4 4.bound(4).assert == 4 5.bound(4).assert == 5 end test 'two arguments' do 4.bound(3,5).assert == 4 3.bound(3,5).assert == 3 5.bound(3,5).assert == 5 2.bound(3,5).assert == 3 6.bound(3,5).assert == 5 end test 'on strings' do 'd'.bound('c','e').assert == 'd' 'c'.bound('c','e').assert == 'c' 'e'.bound('c','e').assert == 'e' 'b'.bound('c','e').assert == 'c' 'f'.bound('c','e').assert == 'e' end end end facets-2.9.3/test/core/comparable/test_cmp.rb0000644000004100000410000000031611714455226021210 0ustar www-datawww-datacovers 'facets/comparable/cmp' test_case Comparable do method :cmp do test 'on integers' do 3.cmp(4).assert == -1 3.cmp(3).assert == 0 3.cmp(2).assert == 1 end end end facets-2.9.3/test/core/comparable/test_op_get.rb0000644000004100000410000000222711714455226021711 0ustar www-datawww-datacovers 'facets/comparable/op_get' test_case Comparable do class_method :[] do test do c = Class.new do include Comparable[:a,:b] attr_accessor :a, :b def initialize(a,b) @a=a; @b=b end end a = [c.new(10,20),c.new(10,30)] a.sort.assert == a a = [c.new(10,30),c.new(10,20)] a.sort.assert == a.reverse a = [c.new(10,10),c.new(20,10)] a.sort.assert == a a = [c.new(20,10),c.new(10,10)] a.sort.assert == a.reverse a = [c.new(10,30),c.new(20,10)] a.sort.assert == a end =begin class_method :sort_on do test do c = Class.new c.class_eval { def initialize(a,b) @a=a; @b=b end sort_on :a,:b } a = [c.new(10,20),c.new(10,30)] assert_equal( a, a.sort ) a = [c.new(10,30),c.new(10,20)] assert_equal( a.reverse, a.sort ) a = [c.new(10,10),c.new(20,10)] assert_equal( a, a.sort ) a = [c.new(20,10),c.new(10,10)] assert_equal( a.reverse, a.sort ) a = [c.new(10,30),c.new(20,10)] assert_equal( a, a.sort ) end end =end end end facets-2.9.3/test/core/comparable/test_cap.rb0000644000004100000410000000073711714455226021203 0ustar www-datawww-datacovers 'facets/comparable/cap' test_case Comparable do method :cap do test do 3.cap(4).assert == 3 4.cap(4).assert == 4 5.cap(4).assert == 4 end end method :at_most do test do 3.at_most(4).assert == 3 4.at_most(4).assert == 4 5.at_most(4).assert == 4 end end method :at_least do test do 3.at_least(4).assert == 4 4.at_least(4).assert == 4 5.at_least(4).assert == 5 end end end facets-2.9.3/test/core/comparable/test_clip.rb0000644000004100000410000000115611714455226021363 0ustar www-datawww-datacovers 'facets/comparable/clip' test_case Comparable do method :clip do test 'single argument' do 3.clip(4).assert == 4 4.clip(4).assert == 4 5.clip(4).assert == 5 end test 'two arguments' do 4.clip(3,5).assert == 4 3.clip(3,5).assert == 3 5.clip(3,5).assert == 5 2.clip(3,5).assert == 3 6.clip(3,5).assert == 5 end test 'on strings' do 'd'.clip('c','e').assert == 'd' 'c'.clip('c','e').assert == 'c' 'e'.clip('c','e').assert == 'e' 'b'.clip('c','e').assert == 'c' 'f'.clip('c','e').assert == 'e' end end end facets-2.9.3/test/core/nilclass/0000755000004100000410000000000011714455226016550 5ustar www-datawww-datafacets-2.9.3/test/core/nilclass/test_to_f.rb0000644000004100000410000000020411714455226021057 0ustar www-datawww-datacovers 'facets/nilclass/to_f' test_case NilClass do method :to_f do test do nil.to_f.assert == 0 end end end facets-2.9.3/test/core/range/0000755000004100000410000000000011714455226016034 5ustar www-datawww-datafacets-2.9.3/test/core/range/test_to_r.rb0000644000004100000410000000035511714455226020366 0ustar www-datawww-datacovers 'facets/range/to_r' test_case Range do method :to_r do test do a = (0..10) a.to_r.assert == a end end method :to_range do test do a = (0..10) a.to_range.assert == a end end end facets-2.9.3/test/core/range/test_overlap.rb0000644000004100000410000000027011714455226021067 0ustar www-datawww-datacovers 'facets/range/overlap' test_case Range do method :overlap? do test do assert( (4..5).overlap?(3..6) ) assert(! (7..9).overlap?(3..6) ) end end end facets-2.9.3/test/core/range/test_combine.rb0000644000004100000410000000103211714455226021030 0ustar www-datawww-datacovers 'facets/range/combine' test_case Range do method :combine do test do r = 0..4 r = r.combine(2..6, 6..10, 13..17, 12..19) x = [0..10, 12..19] r.assert == x end end class_method :combine do test do r = Range.combine(0..4, 2..6, 6..10, 13..17, 12..19) x = [0..10, 12..19] r.assert == x end test "arrays as intervals" do r = Range.combine([0, 4], [2, 6], [6, 10], [13, 17], [12, 19]) x = [[0, 10], [12, 19]] r.assert == x end end end facets-2.9.3/test/core/range/test_umbrella.rb0000644000004100000410000000131611714455226021224 0ustar www-datawww-datacovers 'facets/range/umbrella' test_case Range do method :umbrella do test do (3..6).umbrella(3..6).assert == [0,0] (3...6).umbrella(3...6).assert == [0,0] end test "partially aligned" do (3..6).umbrella(2..6).assert == [1,0] (3..6).umbrella(3..7).assert == [0,1] (3..6).umbrella(4..6).assert == [-1,0] (3..6).umbrella(3..5).assert == [0,-1] end test "offset" do (3..6).umbrella(2..7).assert == [1,1] (3..6).umbrella(4..7).assert == [-1,1] (3..6).umbrella(2..5).assert == [1,-1] (3..6).umbrella(4..5).assert == [-1,-1] end test "offset by exclusion" do (10...20).umbrella(10..20).assert == [0,1] end end end facets-2.9.3/test/core/range/test_within.rb0000644000004100000410000000064411714455226020726 0ustar www-datawww-datacovers 'facets/range/within' test_case Range do method :within? do test "wholy within range" do assert( (4..5).within?(3..6) ) end test "sentinals are equal" do assert( (3..6).within?(3..6) ) end test "lower sentinal out of range" do assert(! (2..5).within?(3..6) ) end test "upper sentinal out of range" do assert(! (5..7).within?(3..6) ) end end end facets-2.9.3/test/core/filetest/0000755000004100000410000000000011714455226016557 5ustar www-datawww-datafacets-2.9.3/test/core/filetest/test_root.rb0000644000004100000410000000022211714455226021122 0ustar www-datawww-datacovers 'facets/filetest/root' test_case FileTest do class_method :root? do test do assert FileTest.root?('/') end end end facets-2.9.3/test/core/indexable_tc.rb0000644000004100000410000001013111714455226017702 0ustar www-datawww-datacovers 'facets/indexable' covers 'facets/array/indexable' test_case Indexable do method :head do test do [1,2,3].head.assert == [1] end end method :tail do test do [1,2,3].tail.assert == [2,3] end end method :foot do test do [1,2,3].foot.assert == [3] end end method :body do test do [1,2,3].body.assert == [1,2] end end method :mid do test do %w{W o r l d}.mid.assert == 'r' %w{W o r l d}.mid(1).assert == 'l' %w{W o r l d}.mid(-1).assert == 'o' end end method :mid do test do a = [1,2,3,4,5] b = [1,2,3,4,5,6] a.mid.assert == 3 b.mid.assert == 4 a.mid(1).assert == 4 b.mid(1).assert == 5 b.mid(2).assert == 6 b.mid(-1).assert == 3 end end method :middle do test do [1,2,3,4,5].middle.assert == [3] [1,2,3,4,5,6].middle.assert == [3,4] end end method :middle do test do %w{W o r l d}.middle.assert == ['r'] %w{W o r l d y}.middle.assert == ['r', 'l'] end end method :middle do test do [1,2,3,4,5].middle(1).assert == [2,3,4] [1,2,3,4,5,6].middle(1).assert == [2,3,4,5] end end method :from do test do %w{W o r l d}.from(3).assert == %w{l d} end end method :thru do test "single parameter" do a = [1,2,3,4,5] r = a.thru(3) r.assert == [1,2,3,4] end test "dual parameter" do a = [1,2,3,4,5] r = a.thru(3,4) r.assert == [4,5] end test do [0,1,2,3,4,5].thru(2,4).assert == [2,3,4] [0,1,2,3,4,5].thru(0,1).assert == [0,1] end end # to be deprecated method :index_of do test do [1,2,3,4].index_of{ |e| e == 3 }.assert == 2 [1,2,3,4].index_of{ |e| e > 3 }.assert == 3 end end method :first= do test do a = [1,2,3] a.first = 9 a.assert == [9,2,3] end end method :last= do test do a = [1,2,3] a.last = 9 a.assert == [1,2,9] end end method :ends do test do [1,2,3,4,5].ends.assert == 4 end end method :pos do test do [1,2,3,4,5].pos(1).assert == 0 [1,2,3,4,5].pos(-1).assert == 4 end end method :range do test do ['a','b','c','d'].range.assert == (0..3) ['a','b','c','d'].range('b','d').assert == (1..3) end end method :range do test do a = [1,2,3,4,5] b = [1,2,3,4,5,6] a.range.assert == (0..4) b.range.assert == (0..5) a.range(2,4).assert == (1..3) b.range(2,3).assert == (1..2) b.range(4,2).assert == (3..1) end end # We can't use an Array to test the following methods b/c # Array handles them specially, either for efficency reasons, # or becuase the have been added to Ruby as of 1.8.7+. setup "special Indexable object" do @c = Class.new do include Indexable def initialize(*a); @a = a; end def slice(*a) ; @a.slice(*a) ; end def splice(*a) ; @a.splice(*a) ; end def size ; @a.size ; end def to_a ; @a ; end end end method :first do test do a = @c.new(1,2,3,4,5) r = a.first(3) r.assert == [1,2,3] end end method :last do test do a = @c.new(1,2,3,4,5) r = a.last(3) r.assert == [3,4,5] end end method :first! do test do a = @c.new(1,2,3,4,5) e = a.first! e.assert == 1 a.to_a.assert == [2,3,4,5] end end method :last! do test do a = @c.new(1,2,3,4,5) e = a.last! e.assert == 5 a.to_a.assert == [1,2,3,4] end end method :index do test do @c.new(1,2,3,4).index{ |e| e == 3 }.assert == 2 @c.new(1,2,3,4).index{ |e| e > 3 }.assert == 3 end end #method :[] do # test do # a = ['a','b','c','d','e','f'] # assert_equal( ['b','f'], a[[1,-1]] ) # end #end #method :[]= do # test do # a = ['a','o','z'] # a[[0,2]] = ['A','Z'] # assert_equal( ['A','o','Z'], a ) # a[[0,-1]] = ['W','Y'] # assert_equal( ['W','o','Y'], a ) # end #end end facets-2.9.3/test/core/regexp/0000755000004100000410000000000011714455226016232 5ustar www-datawww-datafacets-2.9.3/test/core/regexp/test_to_re.rb0000644000004100000410000000037611714455226020734 0ustar www-datawww-datacovers 'facets/regexp/to_re' test_case Regexp do method :to_re do test do r = /0..10/ r.to_re.assert == r.to_re end end method :to_regexp do test do r = /0..10/ r.to_regexp.assert == r end end end facets-2.9.3/test/core/regexp/test_multiline.rb0000644000004100000410000000033211714455226021616 0ustar www-datawww-datacovers 'facets/regexp/multiline' test_case Regexp do method :multiline? do test do re = /x/m re.assert.multiline? end test do re = /x/ re.refute.multiline? end end end facets-2.9.3/test/core/regexp/test_op_add.rb0000644000004100000410000000024011714455226021040 0ustar www-datawww-datacovers 'facets/regexp/op_add' test_case Regexp do method :+ do test do r = /a/ + /b/ r.assert == /(?-mix:a)(?-mix:b)/ end end end facets-2.9.3/test/core/regexp/test_arity.rb0000644000004100000410000000057511714455226020755 0ustar www-datawww-datacovers 'facets/regexp/arity' test_case Regexp do method :arity do test do r = /(1)(2)(3)/ r.arity.assert == 3 end test do r = /(1)(2)(3)(4)/ r.arity.assert == 4 end test do r = /(1)(2)((a)3)/ r.arity.assert == 4 end test do r = /(?#nothing)(1)(2)(3)(?=3)/ r.arity.assert == 3 end end end facets-2.9.3/test/core/regexp/test_op_or.rb0000644000004100000410000000024711714455226020737 0ustar www-datawww-datacovers 'facets/regexp/op_or' test_case Regexp do method :| do test do re = /a/ | /b/ re.assert =~ "a" re.assert =~ "b" end end end facets-2.9.3/test/core/array/0000755000004100000410000000000011714455226016056 5ustar www-datawww-datafacets-2.9.3/test/core/array/test_first.rb0000644000004100000410000000031611714455226020571 0ustar www-datawww-datacovers 'facets/array/indexable' test_case Array do method :first! do test "alias of shift" do a = [1,2,3] r = a.first! r.assert == 1 a.assert == [2,3] end end end facets-2.9.3/test/core/array/test_nonuniq.rb0000644000004100000410000000044411714455226021133 0ustar www-datawww-datacovers 'facets/array/nonuniq' test_case Array do method :nonuniq do test do a = [1,1,2,2,3,4,5] a.nonuniq.sort.assert == [1,2] end end method :nonuniq! do test do a = [1,1,2,2,3,4,5] a.nonuniq! a.sort.assert == [1,2] end end end facets-2.9.3/test/core/array/test_traverse.rb0000644000004100000410000000057711714455226021306 0ustar www-datawww-datacovers 'facets/array/traverse' test_case Array do method :traverse do test do a = ["A", "B", ["X", "Y"]] g = a.traverse{ |e| e.downcase } g.assert == ["a", "b", ["x", "y"]] end end method :traverse! do test do a = ["A", "B", ["X", "Y"]] a.traverse!{ |e| e.downcase } a.assert == ["a", "b", ["x", "y"]] end end end facets-2.9.3/test/core/array/test_rotate.rb0000644000004100000410000000100211714455226020731 0ustar www-datawww-datacovers 'facets/array/rotate' test_case Array do method :rotate do test "clockwise" do a = [1,2,3] r = a.rotate r.assert == [2,3,1] end test "counter-clockwise" do a = [1,2,3] r = a.rotate(-1) r.assert == [3,1,2] end end method :rotate! do test "clockwise" do a = [1,2,3] a.rotate! a.assert == [2,3,1] end test "counter-clockwise" do a = [1,2,3] a.rotate!(-1) a.assert == [3,1,2] end end end facets-2.9.3/test/core/array/test_collapse.rb0000644000004100000410000000024711714455226021247 0ustar www-datawww-datacovers 'facets/array/collapse' test_case Array do method :collapse do test do [1,nil,[1,2],nil,[[3]]].collapse.assert == [1,1,2,3] end end end facets-2.9.3/test/core/array/test_splice.rb0000644000004100000410000000042011714455226020715 0ustar www-datawww-datacovers 'facets/array/splice' test_case Array do method :splice do test do a = [1,2,3] a.splice(1).assert == 2 a.assert == [1,3] end test do a = [1,2,3] a.splice(1,4).assert == 4 a.assert == [1,4,3] end end end facets-2.9.3/test/core/array/test_product.rb0000644000004100000410000000244411714455226021126 0ustar www-datawww-datacovers 'facets/array/product' test_case Array do method :product do test "single argument" do r = [1,2,3].product([4,5,6]) x = [[1, 4],[1, 5],[1, 6],[2, 4],[2, 5],[2, 6],[3, 4],[3, 5],[3, 6]] r.assert == x end test "multiple arguments" do a = %w|a b| b = %w|a x| c = %w|x y| r = a.product(b, c) x = [ ["a", "a", "x"], ["a", "a", "y"], ["a", "x", "x"], ["a", "x", "y"], ["b", "a", "x"], ["b", "a", "y"], ["b", "x", "x"], ["b", "x", "y"] ] r.assert == x end end #def test_product_01 # i = [[1,2], [4], ["apple", "banana"]] # o = [[1, 4, "apple"], [1, 4, "banana"], [2, 4, "apple"], [2, 4, "banana"]] # assert_equal( o, Enumerable.product(*i) ) #end # def test_op_mod # a = [:A,:B,:C] # assert_equal( a[1], a/1 ) # assert_equal( :B, a/1 ) # end # # def test_op_div # a = [:A,:B,:C] # assert_equal( a[1], a/1 ) # assert_equal( :B, a/1 ) # end #def test_op_mod # a = [:A,:B,:C] # assert_equal( a[1], a/1 ) # assert_equal( :B, a/1 ) #end # #def test_op_div # a = [:A,:B,:C] # assert_equal( a[1], a/1 ) # assert_equal( :B, a/1 ) #end end facets-2.9.3/test/core/array/test_mode.rb0000644000004100000410000000031611714455226020366 0ustar www-datawww-datacovers 'facets/array/mode' test_case Array do method :mode do test do [1, 1, 2, 3].mode.assert == [1] end test do [1, 1, 2, 2, 3].mode.sort.assert == [1,2] end end end facets-2.9.3/test/core/array/test_poke.rb0000644000004100000410000000041411714455226020377 0ustar www-datawww-datacovers 'facets/array/pull' test_case Array do method :poke do test do a = [1,2,3] a.poke(9) a.assert == [9,1,2,3] end test do a = [2,3] a.poke(1).assert == [1,2,3] a.poke(4).assert == [4,1,2,3] end end end facets-2.9.3/test/core/array/test_merge.rb0000644000004100000410000000046611714455226020547 0ustar www-datawww-datacovers 'facets/array/merge' test_case Array do method :merge do test do a = [1,2,3] b = [3,4,5] a.merge(b).assert == [1,2,3,4,5] end end method :merge! do test do a = [1,2,3] b = [3,4,5] a.merge!(b) a.assert == [1,2,3,4,5] end end end facets-2.9.3/test/core/array/test_delete.rb0000644000004100000410000000111711714455226020704 0ustar www-datawww-datacovers 'facets/array/delete' test_case Array do method :delete_unless do test do a = [1,2,3] a.delete_unless{ |e| e == 2 } a.assert == [2] end end method :delete_values do test do a = [1,2,3,4] a.delete_values(1,2).assert == [1,2] a.assert == [3,4] end end method :delete_values_at do test do a = [1,2,3,4] a.delete_values_at(1,2).assert == [2,3] a.assert == [1,4] end test do a = [1,2,3,4] a.delete_values_at(0..2).assert == [1,2,3] a.assert == [4] end end end facets-2.9.3/test/core/array/test_last.rb0000644000004100000410000000031111714455226020400 0ustar www-datawww-datacovers 'facets/array/indexable' test_case Array do method :last! do test "alias of pop" do a = [1,2,3] r = a.last! r.assert == 3 a.assert == [1,2] end end end facets-2.9.3/test/core/array/test_recurse.rb0000644000004100000410000000166111714455226021116 0ustar www-datawww-datacovers 'facets/array/recurse' test_case Array do method :recurse do test do a = ["a", ["b", "c", nil], nil] r = a.recurse{|a| a.compact! } r.assert ["a", ["b", "c"]] end test "with Hashes" do require 'facets/hash/recurse' objects = [] struct = [1, 2, {:a => 3, :b => [4, 5, {:c=>6}]}, [7, 8]] struct.recurse(Array, Hash){|o| objects << o; o } objects.assert.include?( [7, 8] ) objects.assert.include?( {:c=>6} ) objects.assert.include?( [4, 5, {:c=>6}] ) objects.assert.include?( {:a => 3, :b => [4, 5, {:c=>6}]} ) objects.assert.include?( struct ) objects.length.assert == 5 end end method :recurse! do test do a = ["a", ["b", "c", nil], nil] a.recurse!{|a| a.compact! } a.assert ["a", ["b", "c"]] end end end facets-2.9.3/test/core/array/test_store.rb0000644000004100000410000000042011714455226020572 0ustar www-datawww-datacovers 'facets/array/store' test_case Array do method :store do test do a = [1,2,3,4,5] a.store(0, :A) a.assert == [:A,2,3,4,5] end test do a = [1,2,3,4,5] a.store(-1, :Z) a.assert == [1,2,3,4,:Z] end end end facets-2.9.3/test/core/array/test_contains.rb0000644000004100000410000000026411714455226021262 0ustar www-datawww-datacovers 'facets/array/contains' test_case Array do method :contains? do test do [1,2,3,4].assert.contains?(2) [1,2,3,4].refute.contains?(9) end end end facets-2.9.3/test/core/array/test_median.rb0000644000004100000410000000071011714455226020675 0ustar www-datawww-datacovers 'facets/array/median' test_case Array do method :median do test "odd sized" do r = %w{e a b c d}.median r.assert == "c" end test "even sized" do r = %w{f e a b c d}.median r.assert == "d" end test "with positive offset" do r = %w{e a b c d}.median(1) r.assert == "d" end test "with negative offset" do r = %w{e a b c d}.median(-1) r.assert == "b" end end end facets-2.9.3/test/core/array/test_conjoin.rb0000644000004100000410000000224311714455226021102 0ustar www-datawww-datacovers 'facets/array/conjoin' test_case Array do method :conjoin do setup "any array" do @a = [1,2,3,4] end test "like join but spaced" do @a.conjoin.assert == "1 2 3 4" end test "comma+space and 'and' on tail" do @a.conjoin(', ', ' and ').assert = "1, 2, 3 and 4" end test "comma+space and 'or' on tail using :last option" do @a.conjoin(', ', :last => ' or ').assert == "1, 2, 3 or 4" end test "semicolon+space and ampersand on tail using index" do @a.conjoin('; ', -1 => ' & ').assert == "1; 2; 3 & 4" end test "with block to determine separator" do r = @a.conjoin{ |i, a, b| i % 2 == 0 ? '.' : '-' } r.assert == "1.2-3.4" end test "very esoteric transformation" do r = @a.conjoin{ |i, x, y| "<#{i} #{x} #{y}>" } r.assert == "1<0 1 2>2<1 2 3>3<2 3 4>4" end test "with :space option" do r = @a.conjoin(',', '&', :space=>2) r.assert == "1 , 2 , 3 & 4" end test ":spacer option can set an alternate spacing string" do r = @a.conjoin('|', '>', :space=>2, :spacer=>'-') r.assert == "1--|--2--|--3-->--4" end end end facets-2.9.3/test/core/array/test_only.rb0000644000004100000410000000035611714455226020427 0ustar www-datawww-datacovers 'facets/array/only.rb' test_case Array do method :only do test do [5].only.assert == 5 [nil].only.assert == nil expect(IndexError){ [].only } expect(IndexError){ [1,2,3].only } end end end facets-2.9.3/test/core/array/test_not_empty.rb0000644000004100000410000000027411714455226021463 0ustar www-datawww-datacovers 'facets/array/not_empty' test_case Array do method :not_empty? do test do [].refute.not_empty? end test do [1,2].assert.not_empty? end end end facets-2.9.3/test/core/array/test_pad.rb0000644000004100000410000000107511714455226020211 0ustar www-datawww-datacovers 'facets/array/pad' test_case Array do method :pad do test do r = [0,1,2,3].pad(7,"x") x = [0,1,2,3,"x","x","x"] r.assert == x end test "negative index" do r = [0,1,2,3].pad(-7,"n") x = ["n","n","n",0,1,2,3] r.assert == x end end method :pad! do test do a = [0,1,2,3] r = a.pad!(6,"y") x = [0,1,2,3,"y","y"] r.assert == x end test "negative index" do a = [0,1,2,3] r = a.pad!(-6,"q") x = ["q","q",0,1,2,3] r.assert == x end end end facets-2.9.3/test/core/array/test_pull.rb0000644000004100000410000000024611714455226020420 0ustar www-datawww-datacovers 'facets/array/pull' test_case Array do method :pull do test do a = [1,2,3] a.pull.assert == 1 a.assert == [2,3] end end end facets-2.9.3/test/core/array/test_split.rb0000644000004100000410000000043411714455226020576 0ustar www-datawww-datacovers 'facets/array/split' test_case Array do method :split do test do ['a','b','c'].split('b').assert == [['a'], ['c']] end test "empty" do [].split('a').assert == [] end test "same" do ['a'].split('a').assert == [] end end end facets-2.9.3/test/core/array/test_select.rb0000644000004100000410000000031311714455226020716 0ustar www-datawww-datacovers 'facets/array/select' test_case Array do method :select! do test do a = [1,2,3,4,5,6,7,8,9,10] a.select!{ |e| e % 2 == 0 } a.assert == [2,4,6,8,10] end end end facets-2.9.3/test/core/array/test_probability.rb0000644000004100000410000000037711714455226021771 0ustar www-datawww-datacovers 'facets/array/probability' test_case Array do method :probability do test do %w{a b}.probability.assert == {'a'=>0.5, 'b'=>0.5} end test do %w{a a a b}.probability.assert == {'a'=>0.75, 'b'=>0.25} end end end facets-2.9.3/test/core/array/test_index.rb0000644000004100000410000000043711714455226020555 0ustar www-datawww-datacovers 'facets/array/index' test_case Array do method :index do test "can handle a block" do i = [1,2,3].index{ |e| e == 2 } i.assert == 1 end test "when no element is found" do i = [1,2,3].index{ |e| e == 5 } i.assert.nil? end end end facets-2.9.3/test/core/array/test_before.rb0000644000004100000410000000072411714455226020707 0ustar www-datawww-datacovers 'facets/array/before' test_case Array do method :before do setup do @sequence = ['a', 'b', 'c'] end test "returns the previous element" do @sequence.before('b').assert == 'a' @sequence.before('c').assert == 'b' end test "loops around from back to front" do @sequence.before('a').assert == 'c' end test "non-member elements return nil" do @sequence.before('d').assert == nil end end end facets-2.9.3/test/core/array/test_uniq_by.rb0000644000004100000410000000032411714455226021107 0ustar www-datawww-datacovers 'facets/array/uniq_by' test_case Array do method :uniq_by! do test do e = [-5, -4, -3, -2, -1, 0] r = (-5..5).to_a r.uniq_by!{ |i| i*i } r.assert == e end end end facets-2.9.3/test/core/array/test_commonality.rb0000644000004100000410000000106511714455226021777 0ustar www-datawww-datacovers 'facets/array/commonality' test_case Array do method :commonality do test do a = [1,2,2,3,3,3] e = { 2 => [2,2], 3 => [3,3,3] } r = a.commonality r.assert == e end test "with block" do a = [1,2,2,3,3,3] e = {false=>[1, 2, 2], true=>[3, 3, 3]} r = a.commonality{ |x| x > 2 } r.assert == e end end method :collisions do test "alias for commonality" do a = [1,2,2,3,3,3] e = { 2 => [2,2], 3 => [3,3,3] } r = a.collisions r.assert == e end end end facets-2.9.3/test/core/array/test_entropy.rb0000644000004100000410000000044411714455226021144 0ustar www-datawww-datacovers 'facets/array/entropy' test_case Array do method :entropy do test do %w{ a b }.entropy.assert == 1.0 end end method :ideal_entropy do test do %w{ a b }.ideal_entropy.assert == 1.0 %w{ a a b b }.ideal_entropy.assert == 2.0 end end end facets-2.9.3/test/core/array/test_duplicates.rb0000644000004100000410000000067011714455226021602 0ustar www-datawww-datacovers 'facets/array/duplicates' test_case Array do method :duplicates do test do a = [1,1,2,2,3,4,5] a.duplicates.sort.assert == [1,2] end test "with minimum" do a = [0,1,2,3,4,5, 0,1,2,3,4, 0,1,2,3, 0,1,2, 0,1, 0] (1..6).each do |m| d = a.duplicates(m).sort e = [*0..6-m] d.assert == e end end end end facets-2.9.3/test/core/array/test_combination.rb0000644000004100000410000000072011714455226021743 0ustar www-datawww-datacovers 'facets/array/combination' test_case Array do method :combination do test "finds pairs of combinations" do e = [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] a = [1,2,3,4] r = a.combination(2).to_a r.assert == e end test "can also take a block" do e = [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] r = [] a = [1,2,3,4] a.combination(2){ |a,b| r << [a,b] } r.assert == e end end end facets-2.9.3/test/core/array/test_extract_options.rb0000644000004100000410000000054611714455226022674 0ustar www-datawww-datacovers 'facets/array/extract_options' test_case Array do method :extract_options! do test do h = { :x=>1, :y=>1 } a = [:a, :b, h] a.extract_options!.assert == h end end end test_case Hash do method :extractable_options? do test do h = { :x=>1, :y=>1 } h.assert.extractable_options? end end end facets-2.9.3/test/core/array/test_occurent.rb0000644000004100000410000000114211714455226021262 0ustar www-datawww-datacovers 'facets/array/occurent' test_case Array do method :occurent do test "set limit" do a = [1,2,3,4,5, 2,3,4,5, 3,4,5, 4,5, 5] (1..5).each do |m| d = a.occurent(m) d.assert == [m] end end test "range" do a = %w{a b c d e b c d e c d e d e e} a.occurent(1..2).sort.assert == ['a','b'] a.occurent(1..3).sort.assert == ['a','b','c'] a.occurent(2..3).sort.assert == ['b','c'] end end end facets-2.9.3/test/core/array/test_peek.rb0000644000004100000410000000054411714455226020371 0ustar www-datawww-datacovers 'facets/array/pull' test_case Array do method :peek do test do a = [1,2,3] a.peek.assert == 3 a.assert == [1,2,3] end test do a = [1,2,3] a.peek(1).assert == 2 a.assert == [1,2,3] end test do a = [1,2,3] a.peek(-1).assert == 1 a.assert == [1,2,3] end end end facets-2.9.3/test/core/array/test_after.rb0000644000004100000410000000071611714455226020547 0ustar www-datawww-datacovers 'facets/array/after' testcase Array do method :after do setup do @sequence = ['a', 'b', 'c'] end test "returns the following element" do @sequence.after('a').assert == 'b' @sequence.after('b').assert == 'c' end test "loops around from back to front" do @sequence.after('c').assert == 'a' end test "non-member elements return nil" do @sequence.after('d').assert == nil end end end facets-2.9.3/test/core/array/test_divide.rb0000644000004100000410000000030011714455226020677 0ustar www-datawww-datacovers 'facets/array/divide' test_case Array do method :divide do test do r = ['a1','b1','a2','b2'].divide(/^a/) r.assert == [['a1','b1'],['a2','b2']] end end end facets-2.9.3/test/core/array/test_permutation.rb0000644000004100000410000000043611714455226022014 0ustar www-datawww-datacovers 'facets/array/permutation' test_case Array do method :permutation do test do r = [] %w[a b c].permutation{ |x| r << x.join('') } x = ['abc','acb','bac','bca','cab','cba'] x.each do |e| r.assert.include?(e) end end end end facets-2.9.3/test/core/array/test_recursively.rb0000644000004100000410000000124311714455226022016 0ustar www-datawww-datacovers 'facets/array/recursively' test_case Array do method :recursively do test "each" do r = [] [1,2,['a','b']].recursively{ |v| v }.each{ |v| r << v } r.assert == [1,2,'a','b'] end test "map" do a = [1,2,['a','b']] r = a.recursively{ |v| v.reverse }.map{ |v| v.succ } r.assert == [2,3,['c','b']] end test "map!" do a = [1,2,['a','b']] a.recursively{ |v| v }.map!{ |v| v.succ } a.assert == [2,3,['b','c']] end test "with block" do a = [1,2,['a','b', nil], nil] r = a.recursively{ |v| v.compact }.map{ |v| v }.compact r.assert == [1,2,['a','b']] end end end facets-2.9.3/test/core/enumerable/0000755000004100000410000000000011714455226017057 5ustar www-datawww-datafacets-2.9.3/test/core/enumerable/test_none.rb0000644000004100000410000000055211714455226021404 0ustar www-datawww-datacovers 'facets/enumerable/none' test_case Enumerable do method :none? do test do a = [nil, nil] assert( a.none? ) end test do a = [false, false] assert( a.none? ) end test do a = [true, false] assert( ! a.none? ) end test do a = [nil, 1] assert( ! a.none? ) end end end facets-2.9.3/test/core/enumerable/test_frequency.rb0000644000004100000410000000033611714455226022446 0ustar www-datawww-datacovers 'facets/enumerable/frequency' test_case Enumerable do method :frequency do test do %w{a b}.frequency.assert == {'a'=>1,'b'=>1} %w{a a b}.frequency.assert == {'a'=>2,'b'=>1} end end end facets-2.9.3/test/core/enumerable/test_find_yield.rb0000644000004100000410000000371711714455226022561 0ustar www-datawww-datacovers 'facets/enumerable/find_yield' test_case Enumerable do method :find_yield do test "a value" do r = [true].find_yield { |value| value } r.assert == true end test "detects correct value" do r = [1].find_yield { |value| value } r.assert == 1 end test "returns value of block" do r = [1].find_yield { |v| v + 3 } r.assert == 4 end test "detects first truthy value" do r = [false, false, 1].find_yield { |value| value } r.assert == 1 end test "returns value when block is true" do r = [false].find_yield { |value| true } r.assert == true end test "returns early when block is true" do v1 = lambda { :something } v2 = lambda { raise "This shouldn't be called" } r = [v1, v2].find_yield { |obj| obj.call } r.assert == :something end test "returns nil when block returns false for all elements" do r = [1,2,3,4].find_yield { |value| false } r.assert == nil end test "returns nil when no elements in collection" do r = [].find_yield { |v| } r.assert == nil end test "can have return value specified when block isnt true" do r = [1,2,3].find_yield(:a_value){ |value| false } r.assert == :a_value end test "documentation correct" do obj1, obj2 = Object.new, Object.new class << obj1 def foo? false end def foo raise end end class << obj2 def foo? true end def foo "a value" end end obj1.foo?.assert == false obj2.foo?.assert == true obj2.foo.assert == "a value" result = [obj1, obj2].find_yield { |obj| obj.foo if obj.foo? } result.assert == "a value" end end method :map_detect do test "old alias for #find_yield" do r = [true].map_detect{ |value| value } r.assert == true end end end facets-2.9.3/test/core/enumerable/test_group_by.rb0000644000004100000410000000164111714455226022273 0ustar www-datawww-datacovers 'facets/enumerable/group_by' test_case Enumerable do method :group_by do test "for array" do a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] e = {0=>[0, 2, 4, 6, 8], 1=>[1, 3, 5, 7, 9]} r = a.group_by{ |x| x % 2 } #.each{|k, v| v.sort!}) r.assert == e end test "for hash" do h = {0=>0, 1=>1, 2=>2, 3=>3, 4=>4, 5=>5, 6=>6, 7=>7, 8=>8, 9=>9} e = {0=>[[0, 0], [2, 2], [4, 4], [6, 6], [8, 8]], 1=>[[1, 1], [3, 3], [5, 5], [7, 7], [9, 9]]} r = h.group_by{|k, v| v%2}.each{|k, v| v.sort!} r.assert == e end test "for range" do r = (1..5).group_by{ |n| n % 3 } e = { 0 => [3], 1 => [1, 4], 2 => [2,5] } r.assert == e end test "for array of string" do r = ["I had", 1, "dollar and", 50, "cents"].group_by{ |e| e.class } e = { String => ["I had","dollar and","cents"], Fixnum => [1,50] } r.assert == e end end end facets-2.9.3/test/core/enumerable/test_each_by.rb0000644000004100000410000000173211714455226022040 0ustar www-datawww-datacovers 'facets/enumerable/each_by' test_case Enumerable do method :each_by do test "infer groups of two" do e = [[1,2], [3,4], [5,6]] a = [1,2,3,4,5,6] r = [] a.each_by{ |a,b| r << [a,b] } r.assert == e end test "infer groups of three" do e = [[1,2,3],[4,5,nil]] a = [1,2,3,4,5] r = [] a.each_by{ |a,b,c| r << [a,b,c] } r.assert == e end test "specify groups of two" do e = [[1,2],[3,4]] a = [1,2,3,4] r = [] a.each_by(2){ |a,b| r << [a,b] } r.assert == e end test "specify groups of three with splat argument" do e = [ [[1,2,3]], [[4,5,6]] ] a = [1,2,3,4,5,6] r = [] a.each_by(3){ |*a| r << a } r.assert == e end test "specify groups of four with splat argument" do e = [ [[1,2,3,4]], [[5,6,7,8]] ] a = [1,2,3,4,5,6,7,8] r = [] a.each_by(4){ |*a| r << a } r.assert == e end end end facets-2.9.3/test/core/enumerable/test_accumulate.rb0000644000004100000410000000145611714455226022574 0ustar www-datawww-datacovers 'facets/enumerable/accumulate' test_case Enumerable do method :accumulate do test do a = [1,2,3] a.accumulate.succ.assert == [2,3,4] end test do a = [{:ab=>1},{22=>:c}] a.accumulate.values_at(:ab,22).assert == [1,nil,:c] end test "chained twice" do a = [1,2,3] a.accumulate(2).succ.to_s.assert == ['2','3','4'] end test "chained three times" do a = [{:ab=>1},{22=>:c}] a.accumulate(3).keys.to_s.split(//).assert == ['a', 'b', '2'] end test "empty receiver" do a = [] a.accumulate.succ.assert == [] end end method :accumulate_all do test "not uniq entries" do a = [{:ab=>1},{22=>:c}] a.accumulate_all(3).keys.to_s.split(//).assert == ['a', 'b', '2', '2'] end end end facets-2.9.3/test/core/enumerable/test_expand.rb0000644000004100000410000000026311714455226021723 0ustar www-datawww-datacovers 'facets/enumerable/expand' test_case Enumerable do method :expand do test do a = [1,2,2,[1,2]] r = a.expand r == [1,2,2,1,2] end end end facets-2.9.3/test/core/enumerable/test_each_with_object.rb0000644000004100000410000000041011714455226023717 0ustar www-datawww-datacovers 'facets/enumerable/each_with_object' test_case Enumerable do method :each_with_object do test do r = Hash.new(0) a = [1,2,2,3] a.each_with_object(r){ |c, h| h[c] += 1 } r.assert == { 1=>1, 2=>2, 3=>1 } end end end facets-2.9.3/test/core/enumerable/test_filter.rb0000644000004100000410000000050511714455226021730 0ustar www-datawww-datacovers 'facets/enumerable/filter' test_case Enumerable do method :filter do test do x = (1..10000) x = x.filter{ |out,i| out << i if i % 2 == 0 } # like select x = x.filter{ |out,i| out << i + 100 } # like map x = x.take(3) x.assert == [102, 104, 106] end end end facets-2.9.3/test/core/enumerable/test_cluster_by.rb0000644000004100000410000000123211714455226022614 0ustar www-datawww-datacovers 'facets/enumerable/cluster_by' test_case Enumerable do method :cluster_by do test "on an array" do a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] e = [[0, 2, 4, 6, 8], [1, 3, 5, 7, 9]] r = a.cluster_by{|x| x % 2} #.each{|a| a.sort!} r.assert == e end test "on a hash" do h = {0=>0, 1=>1, 2=>2, 3=>3, 4=>4, 5=>5, 6=>6, 7=>7, 8=>8, 9=>9} e = [[[0, 0], [2, 2], [4, 4], [6, 6], [8, 8]], [[1, 1], [3, 3], [5, 5], [7, 7], [9, 9]]] r = h.cluster_by{|k, v| v % 2}.each{|a| a.sort!} r.assert == e end test "on an empty array" do r = [].cluster_by{ |a| a } r.assert == [] end end end facets-2.9.3/test/core/enumerable/test_mash.rb0000644000004100000410000000042011714455226021367 0ustar www-datawww-datacovers 'facets/enumerable/mash' test_case Enumerable do method :mash do test "is an alias for #graph" do a = { :a => 1, :b => 2, :c => 3 } e = { :a => 2, :b => 3, :c => 4 } r = a.mash{ |k,v| {k => v+1} } r.assert == e end end end facets-2.9.3/test/core/enumerable/test_map_send.rb0000644000004100000410000000062411714455226022233 0ustar www-datawww-datacovers 'facets/enumerable/map_send' test_case Enumerable do method :map_send do test do [1,2,3].map_send(:+, 3).assert == [4,5,6] end end #method :map_send do # test do # r = [1,2,3].map_send(:+, 1) # assert_equal(r, [2,3,4]) # end # # test "with_block" do # r = [1,2,3].map_send(:+,1){ |x| x + 1 } # assert_equal(r, [3,4,5]) # end #end end facets-2.9.3/test/core/enumerable/test_exclude.rb0000644000004100000410000000027611714455226022101 0ustar www-datawww-datacovers 'facets/enumerable/exclude' test_case Enumerable do method :exclude? do test do a = [1,2,2,3] a.refute.exclude?(2) a.assert.exclude?(4) end end end facets-2.9.3/test/core/enumerable/test_graph.rb0000644000004100000410000000164111714455226021546 0ustar www-datawww-datacovers 'facets/enumerable/graph' test_case Enumerable do method :graph do test "returns hash" do a = { :a => 1, :b => 2, :c => 3 } e = { :a => 2, :b => 3, :c => 4 } r = a.graph{ |k,v| {k => v+1} } r.assert == e end test "hash of array" do a = { :a => [1,2], :b => [2,3], :c => [3,4] } e = { :a => 2, :b => 6, :c => 12 } r = a.graph{ |k,v| [k, v[0]*v[1] ] } r.assert == e end test "array of array" do a = [ [1,2], [2,3], [3,4] ] e = { [1,2] => 2, [2,3] => 6, [3,4] => 12 } r = a.graph{ |a| [a, a[0]*a[1] ] } r.assert == e end test "squares" do numbers = (1..3) squares = numbers.graph{ |n| [n, n*n] } squares.assert == {1=>1, 2=>4, 3=>9} end test "roots" do numbers = (1..3) sq_roots = numbers.graph{ |n| [n*n, n] } sq_roots.assert == {1=>1, 4=>2, 9=>3} end end end facets-2.9.3/test/core/enumerable/test_map_with_index.rb0000644000004100000410000000052211714455226023441 0ustar www-datawww-datacovers 'facets/enumerable/map_with_index' test_case Enumerable do method :map_with_index do test do a = [1,2,3].map_with_index{ |e,i| e*i } a.assert == [0,2,6] end end method :collect_with_index do test do a = [1,2,3].collect_with_index{ |e,i| e*i } a.assert == [0,2,6] end end end facets-2.9.3/test/core/enumerable/test_every.rb0000644000004100000410000000074111714455226021577 0ustar www-datawww-datacovers 'facets/enumerable/every' test_case Enumerable do method :every do test do a = [1,2,3] (a.every + 3 ).assert == [4,5,6] (a.every - 1).assert == [0,1,2] (a.every.to_s).assert == ['1','2','3'] end test "on Enumerator" do e = [1,2,3].to_enum(:map) r = e.every + 3 r.assert == [4,5,6] end end method :every! do test do a = [1,2,3] a.every! + 3 a.assert == [4,5,6] end end end facets-2.9.3/test/core/enumerable/test_one.rb0000644000004100000410000000064311714455226021227 0ustar www-datawww-datacovers 'facets/enumerable/one' test_case Enumerable do method :one? do test do a = [nil, true] assert( a.one? ) end test do a = [true, false] assert( a.one? ) end test do a = [true, true] assert( ! a.one? ) end test do a = [true, 1] assert( ! a.one? ) end test do a = [1, 1] assert( ! a.one? ) end end end facets-2.9.3/test/core/enumerable/test_sum.rb0000644000004100000410000000106111714455226021245 0ustar www-datawww-datacovers 'facets/enumerable/sum' test_case Enumerable do method :sum do test do [1,2,3].sum.assert == 6 end test 'with block' do a = [1.0, 2.1, 3.2].sum(&:to_i) a.assert == 6 end test 'with identity' do a = [].sum(9) a.assert == 9 a = [1].sum(9) a.assert == 1 end test 'with identity and block' do # notice identity is not effected by block (correct?) a = [].sum(9.1, &:to_i) a.assert == 9.1 a = [1.1].sum(9.1, &:to_i) a.assert == 1 end end end facets-2.9.3/test/core/enumerable/test_take.rb0000644000004100000410000000033111714455226021364 0ustar www-datawww-datacovers 'facets/enumerable/take' test_case Enumerable do method :take do test 'is finite' do infinite = (1..1/0.0) # infinite Enumerable infinite.take(5).assert == [1,2,3,4,5] end end end facets-2.9.3/test/core/enumerable/test_modulate.rb0000644000004100000410000000031611714455226022255 0ustar www-datawww-datacovers 'facets/enumerable/modulate' test_case Enumerable do method :modulate do test do a = [2,4,6,8] r = a.modulate(2) x = [[2,6],[4,8]] r.assert == x end end end facets-2.9.3/test/core/enumerable/test_map_by.rb0000644000004100000410000000121211714455226021706 0ustar www-datawww-datacovers 'facets/enumerable/map_by' test_case Enumerable do method :map_by do test do a = [1,2,3,4,5] r = a.map_by{ |e| [e % 2, e + 1] } r.assert == { 0=>[3,5], 1=>[2,4,6] } end test "works well with a hash" do h = {"A"=>1, "B"=>1, "C"=>1, "D"=>2, "E"=>2} r = h.map_by{ |k,v| [v, k.downcase] } r.assert == {1=>["a", "b", "c"], 2=>["d", "e"]} end test "if only a scalar is returned, #map_by acts like #group_by" do h = {"A"=>1, "B"=>1, "C"=>1, "D"=>2, "E"=>2} r = h.map_by{ |k,v| v } r.assert == {1=>[["A",1], ["B",1], ["C",1]], 2=>[["D",2], ["E",2]]} end end end facets-2.9.3/test/core/enumerable/test_uniq_by.rb0000644000004100000410000000056711714455226022121 0ustar www-datawww-datacovers 'facets/enumerable/uniq_by' test_case Enumerable do method :uniq_by do test do e = [-5, -4, -3, -2, -1, 0] r = (-5..5).to_a.uniq_by{ |i| i*i } r.assert == e end end #method :uniq_by! do # test do # e = [-5, -4, -3, -2, -1, 0] # r = (-5..5).to_a # r.uniq_by!{ |i| i*i } # r.assert == e # end #end end facets-2.9.3/test/core/enumerable/test_per.rb0000644000004100000410000000036311714455226021233 0ustar www-datawww-datacovers 'facets/enumerable/per' test_case Enumerable do method :per do test "map" do e = [1,2,3].per.map (e + 3).assert == [4,5,6] (e - 1).assert == [0,1,2] e.to_s.assert == ['1','2','3'] end end end facets-2.9.3/test/core/enumerable/test_ewise.rb0000644000004100000410000000112211714455226021553 0ustar www-datawww-datacovers 'facets/enumerable/ewise' test_case Enumerable do method :ewise do test do a = [1,2,3] (a.ewise + 3).assert == [4,5,6] (a.ewise + [4,5]).assert == [5,7] (a.ewise.+([4,5],2)).assert == [[5,7],[3,4,5]] (a.ewise.+([4,5],3)).assert == [[5,7],[4,5,6]] end end method :elementwise do test do a = [1,2,3] (a.elementwise + 3).assert == [4,5,6] (a.elementwise + [4,5]).assert == [5,7] (a.elementwise.+([4,5],2)).assert == [[5,7],[3,4,5]] (a.elementwise.+([4,5],3)).assert == [[5,7],[4,5,6]] end end end facets-2.9.3/test/core/enumerable/test_visit.rb0000644000004100000410000000027611714455226021606 0ustar www-datawww-datacovers 'facets/enumerable/visit' test_case Enumerable do method :visit do test do r = [1, 2, 8..9].visit{ |x| x.succ } r.assert == [2, 3, [9, 10]] end end end facets-2.9.3/test/core/enumerable/test_occur.rb0000644000004100000410000000053611714455226021562 0ustar www-datawww-datacovers 'facets/enumerable/occur' test_case Enumerable do method :occur do arr = [:a,:b,:a] test do arr.occur(1).assert == [:b] end test do arr.occur(2).assert == [:a] end test do arr.occur(1..1).assert == [:b] end test do arr.occur{ |n| n % 2 == 0 }.assert == [:a] end end end facets-2.9.3/test/core/enumerable/test_count.rb0000644000004100000410000000075311714455226021600 0ustar www-datawww-datacovers 'facets/enumerable/count' test_case Enumerable do method :count do test "strings" do e = ['a','1','a'] r = e.count('1') r.assert == 1 e = ['a','1','a'] r = e.count('a') r.assert == 2 end test "array of arrays" do e = [['a',2],['a',2],['a',2],['b',1]] r = e.count(['a',2]) r.assert == 3 end test "hash" do e = { :a=>2, 'b'=>1, :c=>2 } r = e.count(2) r.assert == 2 end end end facets-2.9.3/test/core/enumerable/test_defer.rb0000644000004100000410000000074111714455226021532 0ustar www-datawww-datacovers 'facets/enumerable/defer' test_case Enumerable do method :defer do source = (1...1/0.0) test do Denumerator.assert === [1,2,3,4].defer end test "without block" do a = source.defer a.class.assert == Denumerator a.take(5).to_a.assert == [1,2,3,4,5] end test "with block" do a = source.defer { |out,i| out << i*2 } a.class.assert == Denumerator a.take(5).to_a.assert == [2,4,6,8,10] end end end facets-2.9.3/test/core/enumerable/test_compact_map.rb0000644000004100000410000000075011714455226022730 0ustar www-datawww-datacovers 'facets/enumerable/compact_map' test_case Enumerable do method :compact_map do test do r = [1,2,nil,4].compact_map { |e| e } r.assert == [1,2,4] end end method :compact_collect do test do r = [1,2,nil,4].compact_collect { |e| e } r.assert == [1,2,4] end end #method :filter_collect do # e = [3,4] # a = [1,2,3,4].filter_collect { |n| # throw(:skip) if n < 3 # n # } # assert_equal( e, a ) #end end facets-2.9.3/test/core/enumerable/test_recursively.rb0000644000004100000410000000106711714455226023023 0ustar www-datawww-datacovers 'facets/enumerable/recursively' test_case Enumerable do method :recursively do c = Class.new do include Enumerable def initialize(ary) @ary = ary end def each(&b) @ary.each(&b) end end test "each" do e = c.new [1,2,['a','b']] a = [] e.recursively(Enumerable).each{ |v| a << v } a.assert == [1,2,'a','b'] end test "map" do e = c.new [1,2,['a','b']] a = e.recursively(Enumerable).map{ |v| v.succ } a.assert == [2,3,['b','c']] end end end facets-2.9.3/test/core/enumerable/test_purge.rb0000644000004100000410000000057311714455226021572 0ustar www-datawww-datacovers 'facets/enumerable/purge' test_case Enumerable do method :purge do test do [1, nil, 2].purge.assert == [1,2] end test "with trash arguments" do (1..6).purge(3,4).assert == [1,2,5,6] end test "with block" do (1..6).purge(0){ |n| n % 2 }.assert == [1,3,5] (1..6).purge(1){ |n| n % 2 }.assert == [2,4,6] end end end facets-2.9.3/test/core/unboundmethod/0000755000004100000410000000000011714455226017613 5ustar www-datawww-datafacets-2.9.3/test/core/unboundmethod/test_arguments.rb0000644000004100000410000000070311714455226023204 0ustar www-datawww-datacovers 'facets/unboundmethod/arguments' test_case UnboundMethod do method :arguments do test do x = Class.new do def foo(a, b); end def bar(a, b=1); end end foomethod = x.instance_method(:foo) arguments = foomethod.arguments arguments.assert == "a0, a1" barmethod = x.instance_method(:bar) arguments = barmethod.arguments arguments.assert == "a0, *args" end end end facets-2.9.3/test/core/unboundmethod/test_name.rb0000644000004100000410000000037511714455226022124 0ustar www-datawww-datacovers 'facets/unboundmethod/name' test_case UnboundMethod do method :name do test do x = Class.new do def foo; "bar"; end end meth = x.instance_method(:foo) meth.name.to_sym.assert == :foo end end end facets-2.9.3/test/core/matchdata/0000755000004100000410000000000011714455226016666 5ustar www-datawww-datafacets-2.9.3/test/core/matchdata/test_matchset.rb0000644000004100000410000000106111714455226022060 0ustar www-datawww-datacovers 'facets/matchdata/matchset' test_case MatchData do method :matchtree do test do md = /(bb)(cc(dd))(ee)/.match "XXaabbccddeeffXX" md.matchtree.assert == [["bb"], ["cc", ["dd"]], ["ee"]] end test do md = /(bb)c(c(dd))(ee)/.match "XXaabbccddeeffXX" md.matchtree.assert == [["bb"], "c", ["c", ["dd"]], ["ee"]] end end method :matchset do test do md = /(bb)(cc(dd))(ee)/.match "XXaabbccddeeffXX" md.matchset.assert == ["XXaa", [["bb"], ["cc", ["dd"]], ["ee"]], "ffXX"] end end end facets-2.9.3/test/core/matchdata/test_match.rb0000644000004100000410000000027011714455226021345 0ustar www-datawww-datacovers 'facets/matchdata/match' test_case MatchData do method :match do test do md = /X(a)(b)(c)X/.match("YXabcXY") md.match.assert == "XabcX" end end end facets-2.9.3/test/core/file/0000755000004100000410000000000011714455226015657 5ustar www-datawww-datafacets-2.9.3/test/core/file/test_append.rb0000644000004100000410000000066711714455226020523 0ustar www-datawww-datacovers 'facets/file/append' test_case File do class_method :append do setup do require 'fileutils' @test_file = 'tmp/append.txt' FileUtils.rm(@test_file) if File.exist?(@test_file) end test do File.append(@test_file, "line 1\n") File.read(@test_file).assert == "line 1\n" File.append(@test_file, "line 2\n") File.read(@test_file).assert == "line 1\nline 2\n" end end end facets-2.9.3/test/core/file/test_ext.rb0000644000004100000410000000115711714455226020047 0ustar www-datawww-datacovers 'facets/file/ext' test_case File do class_method :ext do test "typical filename" do s = 'file.txt' File.ext(s).assert == 'txt' File.ext(s, 'old').assert == 'file.old' File.ext(s, '').assert == 'file' end test "no extension" do s = 'file' File.ext(s).assert == '' File.ext(s, 'txt').assert == 'file.txt' File.ext(s, '').assert == 'file' end test "non-standard extensions" do s = '.profile' File.ext(s).assert == '' File.ext(s, 'new').assert == '.profile.new' File.ext(s, '').assert == '.profile' end end end facets-2.9.3/test/core/file/test_read_list.rb0000644000004100000410000000043311714455226021211 0ustar www-datawww-datacovers 'facets/file/read_list' test_case File do class_method :read_list do test_file = 'tmp/read_list.txt' test do File.open(test_file, 'w'){ |f| f << "line 1\nline 2\n#line 3" } File.read_list(test_file).assert == ['line 1', 'line 2'] end end end facets-2.9.3/test/core/file/test_rootname.rb0000644000004100000410000000024611714455226021071 0ustar www-datawww-datacovers 'facets/file/rootname' test_case File do class_method :rootname do test do File.rootname('test/core/file').assert == 'test' end end end facets-2.9.3/test/core/file/test_sanitize.rb0000644000004100000410000000123711714455226021074 0ustar www-datawww-datacovers 'facets/file/sanitize' test_case File do # TODO: Write file identity tests. class_method :sanitize do test "spaces become underscores" do File.sanitize('This is a test').assert == "This_is_a_test" end test "Windows-style path dividers" do File.sanitize('This\is\test').assert == "test" end test "Unix-style path dividers" do File.sanitize('This/is/test').assert == "test" end test "non-word characters" do File.sanitize('This/te#$#@!st').assert == "te_____st" end test "initial dot" do File.sanitize('.').assert == "_." File.sanitize('....').assert == "_...." end end end facets-2.9.3/test/core/file/test_rewrite.rb0000644000004100000410000000117511714455226020730 0ustar www-datawww-datacovers 'facets/file/rewrite' test_case File do test_data = 'This is a test!' class_method :rewrite do setup do @test_file = 'tmp/rewrite.txt' File.open(@test_file, 'w'){ |w| w << test_data } end test do File.rewrite(@test_file){ |s| s.reverse } File.read(@test_file).assert == test_data.reverse end end class_method :rewrite! do setup do @test_file = 'tmp/rewrite.txt' File.open(@test_file, 'w'){ |w| w << test_data } end test do File.rewrite!(@test_file){ |s| s.reverse! } File.read(@test_file).assert == test_data.reverse end end end facets-2.9.3/test/core/file/test_split_all.rb0000644000004100000410000000031111714455226021221 0ustar www-datawww-datacovers 'facets/file/split_all' test_case File do class_method :split_all do test do fp = "test/core/file" File.split_all(fp).assert == ['test', 'core', 'file'] end end end facets-2.9.3/test/core/file/test_write.rb0000644000004100000410000000045511714455226020401 0ustar www-datawww-datacovers 'facets/file/write' test_case File do class_method :write do test_file = 'tmp/write.txt' test do data = "Test data\n" nbytes = File.write(test_file, data) out = File.read(test_file) out.assert == data out.size.assert == nbytes end end end facets-2.9.3/test/core/file/test_writelines.rb0000644000004100000410000000060011714455226021424 0ustar www-datawww-datacovers 'facets/file/writelines' #require File.dirname(__FILE__) + '/helpers/mockfile' test_case File do class_method :writelines do test_file = 'tmp/writelines.txt' test_data = %w[one two three four five] test do File.writelines(test_file, test_data) out = File.readlines(test_file) out.map{ |l| l.chomp }.assert == test_data end end end facets-2.9.3/test/core/file/test_read_binary.rb0000644000004100000410000000053211714455226021522 0ustar www-datawww-datacovers 'facets/file/read_binary' test_case File do # TODO: Is this even really testable? class_method :read_binary do test_file = 'tmp/read_binary.txt' test_data = "line 1\nline 2\nline 3" test do File.open(test_file, 'w'){ |f| f << test_data } File.read_binary(test_file).assert == test_data end end end facets-2.9.3/test/core/file/test_create.rb0000644000004100000410000000040711714455226020507 0ustar www-datawww-datacovers 'facets/file/create' test_case File do class_method :create do test_file = 'tmp/rewrite.txt' test_data = 'This is a test!' test do File.create(test_file, test_data) File.read(test_file).assert == test_data end end end facets-2.9.3/test/core/file/test_null.rb0000644000004100000410000000017711714455226020222 0ustar www-datawww-datacovers 'facets/file/null' test_case File do class_method :null do test do assert File.null end end end facets-2.9.3/test/core/exception/0000755000004100000410000000000011714455226016736 5ustar www-datawww-datafacets-2.9.3/test/core/exception/test_detail.rb0000644000004100000410000000030311714455226021560 0ustar www-datawww-datacovers 'facets/exception/detail' test_case Exception do method :detail do test "at least it runs" do err = ArgumentError.new("example error") err.detail end end end facets-2.9.3/test/core/exception/test_raised.rb0000644000004100000410000000027011714455226021570 0ustar www-datawww-datacovers 'facets/exception/raised' test_case Exception do class_method :raised? do test do NameError.raised? do supercalafragalistic end end end end facets-2.9.3/test/core/exception/test_suppress.rb0000644000004100000410000000027511714455226022212 0ustar www-datawww-datacovers 'facets/exception/suppress' test_case Exception do class_method :suppress do test do NameError.suppress do supercalafragalistic end end end end facets-2.9.3/test/core/numeric/0000755000004100000410000000000011714455226016402 5ustar www-datawww-datafacets-2.9.3/test/core/numeric/test_distance.rb0000644000004100000410000000032411714455226021557 0ustar www-datawww-datacovers 'facets/numeric/distance' test_case Numeric do method :distance do test do 10.distance(6).assert == 4 10.distance(8).assert == 2 7.distance(9).assert == -2 end end end facets-2.9.3/test/core/numeric/test_spacing.rb0000644000004100000410000000050711714455226021414 0ustar www-datawww-datacovers 'facets/numeric/spacing' test_case Numeric do method :spacing do test do samples = [-10.5, -3, 3, 1.0e14, 10000, 14.5e10] samples.each do |numeric_item| numeric_item.spacing.assert == numeric_item.to_s.size numeric_item.spacing.assert.kind_of?(Integer) end end end end facets-2.9.3/test/core/numeric/test_length.rb0000644000004100000410000000027111714455226021247 0ustar www-datawww-datacovers 'facets/numeric/length' test_case Numeric do method :length do test do (0..10).each do |power| power.length.assert == power end end end end facets-2.9.3/test/core/numeric/test_approx.rb0000644000004100000410000000052411714455226021300 0ustar www-datawww-datacovers 'facets/numeric/approx' test_case Numeric do method :approx? do test do f = 10.006 assert( f.approx?(10, 0.1) ) assert( 100.4.approx?(100.6, 1) ) end end method :close? do test do f = 10.006 assert( f.close?(10, 0.1) ) assert( 100.4.close?(100.6, 1) ) end end end facets-2.9.3/test/core/numeric/test_round.rb0000644000004100000410000000244711714455226021124 0ustar www-datawww-datacovers 'facets/numeric/round' test_case Numeric do f0 = [ 0, 10, 15, 105 ] method :round_at do test "1" do fr = f0.collect{ |f| f.round_at(1) } fr.assert == [0,10,15,105] end test "2" do fr = f0.collect { |f| f.round_at(2) } fr.assert == [0,10,15,105] end end method :round_to do test "0.1" do fr = f0.collect { |f| f.round_to(0.1) } fr.assert == [0,10,15,105] end test "10" do fr = f0.collect { |f| f.round_to(10) } fr.assert == [0,10,20,110] end end #method :round_off do # test do # 1.2.round_off.assert == 1.0 # 1.8.round_off.assert == 2.0 # end #end end test_case Float do f1 = [ 10.1, 10.01, 10.9, 10.09, 10.5, 10.05, 10.49 ] method :round_at do test "1" do fr = f1.collect { |f| f.round_at(1) } fr.assert == [10.1,10.0,10.9,10.1,10.5,10.1,10.5] end test "2" do fr = f1.collect { |f| f.round_at(2) } fr.assert == [10.1,10.01,10.9,10.09,10.5,10.05,10.49] end end method :round_to do test "0.1" do fr = f1.collect { |f| f.round_to(0.1) } fr.assert == [10.1,10.0,10.9,10.1,10.5,10.1,10.5] end test "10" do fr = f1.collect { |f| f.round_to(10) } fr.assert == [10,10,10,10,10,10,10] end end end facets-2.9.3/test/core/functor_tc.rb0000644000004100000410000000107211714455226017433 0ustar www-datawww-datacovers 'facets/functor' test_case Functor do class_method :new do test do fc = Functor.new do |op, *a, &b| [op, a, b] end (fc + 1).assert == [:+, [1], nil] end end method :__class__ do test do fc = Functor.new do |op, *a, &b| [op, a, b] end fc.__class__.assert == Functor end end method :to_proc do test do f = Functor.new do |op, *a| [op, *a] end p = f.to_proc p.assert.is_a? Proc p.call(:+,1,2,3).assert == [:+,1,2,3] end end end facets-2.9.3/test/core/enumerator/0000755000004100000410000000000011714455226017121 5ustar www-datawww-datafacets-2.9.3/test/core/enumerator/test_fx.rb0000644000004100000410000000026111714455226021121 0ustar www-datawww-datacovers 'facets/enumerator/fx' test_case Enumerator do method :fx do test do e = [1,2,3].to_enum r = e.fx + 2 r.assert == [3,4,5] end end end facets-2.9.3/test/core/enumerator/test_new.rb0000644000004100000410000000055711714455226021305 0ustar www-datawww-datacovers 'facets/enumerator' test_case Enumerator do class_method :new do test "with block" do # This example taken from ri19 Enumerator.new fib = Enumerator.new do |y| a = b = 1 loop { y << a a, b = b, a + b } end fib.take(10).assert == [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] end end end facets-2.9.3/test/core/denumerable_tc.rb0000644000004100000410000000745511714455226020251 0ustar www-datawww-datacovers 'facets/denumerable' covers 'facets/enumerable/defer' #require 'facets/enumerable/take' test_case Denumerable do c = Class.new do include Denumerable def initialize(*a) @a = a end def each(&blk) @a.each(&blk) end def size; @a.size; end end method :map do test do o = c.new(1,2,3,4) o.map.assert.is_a?(Denumerator) o.map{ |x| x + 1 }.assert.is_a?(Denumerator) o.map{ |x| x + 1 }.to_a.assert == [2,3,4,5] end end method :collect do test do o = c.new(1,2,3,4) o.collect.assert.is_a?(Denumerator) o.collect{ |x| x + 1 }.assert.is_a?(Denumerator) o.collect{ |x| x + 1 }.to_a.assert == [2,3,4,5] end end method :select do test do o = c.new(1,2,3,4) o.select.assert.is_a?(Denumerator) o.select{ |x| x > 1 }.assert.is_a?(Denumerator) o.select{ |x| x > 1 }.to_a.assert == [2,3,4] end end method :find_all do test do o = c.new(1,2,3,4) o.find_all.assert.is_a?(Denumerator) o.find_all{ |x| x > 1 }.assert.is_a?(Denumerator) o.find_all{ |x| x > 1 }.to_a.assert == [2,3,4] end end method :reject do test do o = c.new(1,2,3,4) o.reject.assert.is_a?(Denumerator) o.reject{ |x| x > 1 }.assert.is_a?(Denumerator) o.reject{ |x| x > 1 }.to_a.assert == [1] end end method :skip do test do o = c.new(1,2,3,4) o.skip(2).assert.is_a?(Denumerator) o.skip(2).to_a.assert == [3,4] end end method :take do test do o = c.new(1,2,3,4) o.take(2).assert.is_a?(Denumerator) o.take(2).to_a.assert == [1,2] end end end test_case Denumerator do source = (1..1/0.0) # infinite Enumerable object method :each do test do res = [] (1..5).defer.each { |i| res << i } res.assert == [1,2,3,4,5] end end method :take do test do d = source.defer d.take(5).to_a.assert == [1,2,3,4,5] end end method :inject do test do d = (1..5).defer d = d.inject({}) { |h,v| h[v] = v*2; h } d.assert == {1=>2,2=>4,3=>6,4=>8,5=>10} end # TODO: problem with break in proc #test do # d = (1..5).defer # d = d.inject({}){ |h,v| h[v] = v*2; break h if v>=3; h } # d.assert == {1=>2,2=>4,3=>6} #end end method :max do test do d = source.defer d.take(5).max.assert == 5 end end method :min do test do d = source.defer d.take(5).min.assert == 1 end end method :sort_by do test do d = source.defer d.take(5).sort_by{ |x| -x }.assert == [5,4,3,2,1] end end method :map do test do d = source.defer d.map{ |i| i*2 }.take(5).min.assert == 2 end end method :defer do test do d = source.defer.defer{ |out,i| out << i*2 } d.take(5).to_a.assert == [2,4,6,8,10] end test "chain" do d = source.defer { |out,i| out.yield(i) if i % 2 == 0 }. defer { |out,i| out.yield(i + 100) } d.take(5).to_a.assert == [102,104,106,108,110] end end method :select do test do d = source.defer d = d.select{ |i| i % 2 == 0 } d.take(5).to_a.assert == [2,4,6,8,10] end end method :find_all do test do d = source.defer d = d.find_all{ |i| i % 2 == 0 } d.take(5).to_a.assert == [2,4,6,8,10] end end method :reject do test do d = source.defer d = d.reject { |i| i % 3 == 0 } d.take(5).to_a.assert == [1,2,4,5,7] end end method :skip do test do d = source.defer d = d.skip(20) d.take(5).to_a.assert == [21,22,23,24,25] end end #method :each_cons # test do # a = source.defer # assert_equal [[1,2,3],[2,3,4],[3,4,5],[4,5,6]], a.each_cons(3).take(4) # end #end end facets-2.9.3/test/core/integer/0000755000004100000410000000000011714455226016375 5ustar www-datawww-datafacets-2.9.3/test/core/integer/test_factorial.rb0000644000004100000410000000066011714455226021727 0ustar www-datawww-datacovers 'facets/integer/factorial' test_case Integer do method :factorial do test do 0.factorial.assert == 1 1.factorial.assert == 1 2.factorial.assert == 2 3.factorial.assert == 6 4.factorial.assert == 24 end end method :fac do test do 0.fac.assert == 1 1.fac.assert == 1 2.fac.assert == 2 3.fac.assert == 6 4.fac.assert == 24 end end end facets-2.9.3/test/core/integer/test_even.rb0000644000004100000410000000065111714455226020720 0ustar www-datawww-datacovers 'facets/integer/even' # NOTE: Can't test on Integer directly b/c Ruby 1.8.7 defines separate # methods for Fixnum. (huh?) test_case Fixnum do method :even? do test "even numbers are even" do (-100..100).step(2) do |n| n.even?.assert == true end end test "odd numbers are not even" do (-101..101).step(2) do |n| n.even?.assert == false end end end end facets-2.9.3/test/core/integer/test_bitmask.rb0000644000004100000410000000221111714455226021407 0ustar www-datawww-datacovers 'facets/integer/bitmask' test_case Integer do method :bit do test do 0.bit(0).assert == 1 0.bit(1).assert == 2 0.bit(2).assert == 4 0.bit(3).assert == 8 end end method :bit do test "negate" do 1.bit(~0).assert == 0 2.bit(~1).assert == 0 4.bit(~2).assert == 0 8.bit(~3).assert == 0 end end method :bit_clear do test do 1.bit_clear(0).assert == 0 2.bit_clear(1).assert == 0 4.bit_clear(2).assert == 0 8.bit_clear(3).assert == 0 end end method :bit? do test do a = 8 assert(! a.bit?(0)) assert(! a.bit?(1)) assert(! a.bit?(2)) assert( a.bit?(3)) assert(! a.bit?(4)) assert(! a.bit?(5)) end end method :bitmask do test do a = 1 m = Bit(4) a = a.bitmask(m) a.assert == 17 assert( a.bitmask?(m) ) end end method :bitmask? do test do 7.assert.bitmask?(7) 7.assert.bitmask?(5) 8.refute.bitmask?(3) end end end test_case Kernel do method :Bit do test do n = Bit(4) n.assert == 16 end end end facets-2.9.3/test/core/integer/test_ordinal.rb0000644000004100000410000000065611714455226021420 0ustar www-datawww-datacovers 'facets/integer/ordinal' test_case Integer do method :ordinal do test do 1.ordinal.assert == '1st' 2.ordinal.assert == '2nd' 3.ordinal.assert == '3rd' 4.ordinal.assert == '4th' end end method :ordinalize do test do 1.ordinalize.assert == '1st' 2.ordinalize.assert == '2nd' 3.ordinalize.assert == '3rd' 4.ordinalize.assert == '4th' end end end facets-2.9.3/test/core/integer/test_odd.rb0000644000004100000410000000064311714455226020532 0ustar www-datawww-datacovers 'facets/integer/odd' # NOTE: Can't test on Integer directly b/c Ruby 1.8.7 defines separate # methods for Fixnum. (huh?) test_case Fixnum do method :odd? do test "odd numbers are odd" do (-101..101).step(2) do |n| n.odd?.assert == true end end test "odd numbers are not even" do (-100..100).step(2) do |n| n.odd?.assert == false end end end end facets-2.9.3/test/core/integer/test_multiple.rb0000644000004100000410000000036411714455226021617 0ustar www-datawww-datacovers 'facets/integer/multiple' test_case Integer do method :multiple? do test do assert( ! 1.multiple?(2) ) assert( 2.multiple?(2) ) assert( ! 5.multiple?(3) ) assert( 6.multiple?(3) ) end end end facets-2.9.3/test/core/integer/test_of.rb0000644000004100000410000000065011714455226020366 0ustar www-datawww-datacovers 'facets/integer/of' test_case Integer do method :of do test do a = 4 b = a.of{ |i| i*2 } b.assert == [0,2,4,6] end end method :times_collect do test do a = 4 b = a.times_collect{ |i| i*2 } b.assert == [0,2,4,6] end end method :times_map do test do a = 4 b = a.times_map{ |i| i*2 } b.assert == [0,2,4,6] end end end facets-2.9.3/test/core/to_hash_tc.rb0000644000004100000410000000716211714455226017406 0ustar www-datawww-datacovers 'facets/to_hash' test_case Array do method :to_h do test do a = [ [:a,1], [:b,2] ] a.to_h.assert == { :a=>1, :b=>2 } end test do a = [ [:a,1,2], [:b,2], [:c], [:d] ] a.to_h.assert == { :a=>[1,2], :b=>[2], :c=>[], :d=>[] } end test do a = [ [:a,1,2], 2, :b, [:c,3], 9 ] a.to_h.assert == { [:a,1,2]=>2, :b=>[:c,3], 9=>nil } end end method :to_h_auto do test do a = [ [:a,1], [:b,2] ] a.to_h_auto.assert == { :a=>1, :b=>2 } end test do a = [ [:a,1,2], [:b,2], [:c], [:d] ] a.to_h_auto.assert == { :a=>[1,2], :b=>[2], :c=>[], :d=>[] } end test do a = [ [:a,1,2], 2, :b, [:c,3], 9 ] a.to_h_auto == { [:a,1,2]=>2, :b=>[:c,3], 9=>nil } end end method :to_h_splat do test do a = [:a,1,:b,2,:c] a.to_h_splat.assert == { :a=>1, :b=>2, :c=>nil } end end method :to_h_flat do test do a = [:a,1,[:b,2,:c]] a.to_h_flat.assert == { :a=>1, :b=>2, :c=>nil } end end method :to_h_assoc do test do a = [ [:a,1,2], [:b,2], [:c], [:d] ] a.to_h_assoc.assert == { :a=>[1,2], :b=>[2], :c=>[], :d=>[] } end end method :to_h_assoc do test do a = [ :x, [:x], [:x,1,2], [:x,3], [:x,4] ] a.to_h_assoc.assert == { :x=>[4] } end end method :to_h_multi do test "#to_h can default to #to_h_multi" do a = [ [:a,1,2], [:b,2], [:c], [:d] ] a.to_h.assert == { :a=>[1,2], :b=>[2], :c=>[], :d=>[] } end test do a = [ [:a,1,2], [:a,3], [:a,4], [:a], :a ] a.to_h_multi.assert == { :a=>[1,2,3,4] } end end #method :to_hash do #end end test_case Hash do method :to_h do test do {"a"=>1,"b"=>2}.to_h.assert == {"b"=>2,"a"=>1} end end method :to_hash do test do h = {:a=>1, :b=>2} h.to_hash.assert == h end end end test_case Enumerable do method :to_h do test do (1..4).to_h.assert == { 1=>2, 3=>4 } end end method :to_h_auto do test do (1..4).to_h_auto.assert == { 1=>2, 3=>4 } end end method :to_h_splat do test do (1..4).to_h_splat.assert == { 1=>2, 3=>4 } end end method :to_h_flat do test do (1..4).to_h_flat.assert == { 1=>2, 3=>4 } end end method :to_h_assoc do test do (1..4).to_h_assoc.assert == { 1=>[], 2=>[], 3=>[], 4=>[] } end end method :to_h_multi do test do (1..4).to_h_multi.assert == { 1=>[], 2=>[], 3=>[], 4=>[] } end end #method :to_hash do # test do # (1..4).to_hash.assert == { 1=>2, 3=>4 } # end #end end test_case Enumerator do method :to_h do test do (1..4).to_enum.to_h.assert == { 1=>2, 3=>4 } end end method :to_h_auto do test do (1..4).to_enum.to_h_auto.assert == { 1=>2, 3=>4 } end end method :to_h_splat do test do (1..4).to_enum.to_h_splat.assert == { 1=>2, 3=>4 } end end method :to_h_flat do test do (1..4).to_enum.to_h_flat.assert == { 1=>2, 3=>4 } end end method :to_h_assoc do test do (1..4).to_enum.to_h_assoc.assert == { 1=>[], 2=>[], 3=>[], 4=>[] } end end method :to_h_multi do test do (1..4).to_enum.to_h_multi.assert == { 1=>[], 2=>[], 3=>[], 4=>[] } end end #method :to_hash do # test do # (1..4).to_hash.assert == { 1=>2, 3=>4 } # end #end end test_case Struct do method :to_h do test do s = Struct.new(:a,:b).new(1,2) s.to_h.assert == {:a=>1, :b=>2} end end end test_case NilClass do method :to_h do test do nil.to_h.assert == {} end end end facets-2.9.3/test/core/binding/0000755000004100000410000000000011714455226016352 5ustar www-datawww-datafacets-2.9.3/test/core/binding/test_eval.rb0000644000004100000410000000025511714455226020667 0ustar www-datawww-datacovers 'facets/binding/eval' test_case Binding do x = "hello" bind = binding method :eval do test do bind.eval("x").assert == "hello" end end end facets-2.9.3/test/core/binding/test_local_variables.rb0000644000004100000410000000125511714455226023063 0ustar www-datawww-datacovers 'facets/binding/local_variables' test_case Binding do a = 1 b = 2 x = "hello" bind = binding unless RUBY_VERSION > "1.9" method :local_variables do test do bind.local_variables.assert.include? "bind" bind.local_variables.assert.include? "x" bind.local_variables.assert.include? "a" bind.local_variables.assert.include? "b" end end else method :local_variables do test do bind.local_variables.assert.include? :bind bind.local_variables.assert.include? :x bind.local_variables.assert.include? :a bind.local_variables.assert.include? :b end end end end facets-2.9.3/test/core/binding/test_defined.rb0000644000004100000410000000027611714455226021341 0ustar www-datawww-datacovers 'facets/binding/defined' test_case Binding do a = 1 b = 2 x = "hello" bind = binding method :defined? do test do bind.assert.defined?("x") end end end facets-2.9.3/test/core/binding/test_self.rb0000644000004100000410000000023711714455226020671 0ustar www-datawww-datacovers 'facets/binding/self' test_case Binding do bind = binding this = self method :self do test do bind.self == this end end end facets-2.9.3/test/core/binding/test_caller.rb0000644000004100000410000000202311714455226021175 0ustar www-datawww-datacovers 'facets/binding/caller' test_case Binding do a = 1 b = 2 x = "hello" bind = binding line = __LINE__ # the line number must be updated if it moves file = __FILE__ # why does it equal basename only? method :__LINE__ do test do bind.__LINE__.assert == line - 1 end end method :__FILE__ do test do bind.__FILE__.assert == file end end method :__DIR__ do test do bind.__DIR__.assert == File.dirname(file) end end method :callstack do test do bind.callstack.assert.is_a?(Array) end end method :call_stack do test do bind.call_stack.assert.is_a?(Array) end end method :caller do test do Exception.refute.raised? do bind.caller end end end method :__callee__ do test do alternate.__callee__.assert == :alternate end end method :__method__ do test do alternate.__method__.assert == :alternate end end # helper method def alternate binding end end facets-2.9.3/test/core/binding/test_op.rb0000644000004100000410000000044011714455226020352 0ustar www-datawww-datacovers 'facets/binding/op' test_case Binding do a = 1 b = 2 x = "hello" bind = binding method :[] do test do bind["x"].assert == "hello" end end method :[]= do test do bind["x"] = "goodbye" bind["x"].assert == "goodbye" end end end facets-2.9.3/test/core/class/0000755000004100000410000000000011714455226016045 5ustar www-datawww-datafacets-2.9.3/test/core/class/test_to_proc.rb0000644000004100000410000000032411714455226021075 0ustar www-datawww-datacovers 'facets/class/to_proc' test_case Class do method :to_proc do test do person = Struct.new(:name) people = ["joe"].map(&person) people[0].name.assert == "joe" end end end facets-2.9.3/test/core/class/test_preallocate.rb0000644000004100000410000000063211714455226021725 0ustar www-datawww-datacovers 'facets/class/preallocate' test_case Class do method :preallocate do setup do @c = Class.new do def f "f" end end @m = Module.new do def f '{' + super + '}' end end end test do m = @m @c.class_eval do preallocate m end x = @c.new x.f.assert == "{f}" end end end facets-2.9.3/test/core/class/test_subclasses.rb0000644000004100000410000000041211714455226021575 0ustar www-datawww-datacovers 'facets/class/subclasses' test_case Class do method :subclasses do # class with a number of subclasses c = Class.new x = Class.new(c) y = Class.new(c) z = Class.new(c) test do c.subclasses == [x, y, z] end end end facets-2.9.3/test/core/class/test_descendents.rb0000644000004100000410000000037511714455226021735 0ustar www-datawww-datacovers 'facets/class/descendants' test_case Class do method :descendants do a = Class.new b = Class.new(a) c = Class.new(b) test do a.descendants.assert.include?(b) a.descendants.assert.include?(c) end end end facets-2.9.3/test/core/string/0000755000004100000410000000000011714455226016246 5ustar www-datawww-datafacets-2.9.3/test/core/string/test_interpolate.rb0000644000004100000410000000031011714455226022152 0ustar www-datawww-datacovers 'facets/string/interpolate' test_case String do class_method :interpolate do test do a = 1 String.interpolate{ 'this is #{a}' }.assert == 'this is 1' end end end facets-2.9.3/test/core/string/test_bytes.rb0000644000004100000410000000024211714455226020756 0ustar www-datawww-datacovers 'facets/string/bytes' test_case String do method :bytes do test do s = "abc" s.bytes.to_a.assert == s.unpack('C*') end end end facets-2.9.3/test/core/string/test_compress_lines.rb0000644000004100000410000000040411714455226022655 0ustar www-datawww-datacovers 'facets/string/compress_lines' test_case String do method :compress_lines do test do string = <<-QUERY.compress_lines SELECT name FROM users QUERY string.assert == "SELECT name FROM users" end end end facets-2.9.3/test/core/string/test_word_wrap.rb0000644000004100000410000000277311714455226021647 0ustar www-datawww-datacovers 'facets/string/word_wrap' test_case String do method :word_wrap do test do e = "abcde\n12345\nxyzwu\n" r = "abcde 12345 xyzwu".word_wrap(5) r.assert == e end test do e = "abcd\n1234\nxyzw\n" r = "abcd 1234 xyzw".word_wrap(4) r.assert == e end test do e = "abc\n123\n" r = "abc 123".word_wrap(4) r.assert == e end test do e = "abc \n123\n" r = "abc 123".word_wrap(4) r.assert == e end test do e = "abc \n123\n" r = "abc 123".word_wrap(4) r.assert == e end # test do # assert_equal "abcde-\n12345-\nxyzwu\n", "abcde12345xyzwu".word_wrap(6,2) # assert_equal "abcd-\n1234-\nxyzw\n", "abcd1234xyzw".word_wrap(5,2) # assert_equal "abc \n123\n", "abc 123".word_wrap(4,2) # assert_equal "abc \n123\n", "abc 123".word_wrap(4,2) # assert_equal "abc \n123\n", "abc 123".word_wrap(4,2) # end end method :word_wrap! do test do w = "abcde 12345 xyzwu" w.word_wrap!(5) w.assert == "abcde\n12345\nxyzwu\n" end test do w = "abcd 1234 xyzw" w.word_wrap!(4) w.assert == "abcd\n1234\nxyzw\n" end test do w = "abc 123" w.word_wrap!(4) w.assert == "abc\n123\n" end test do w = "abc 123" w.word_wrap!(4) w.assert == "abc \n123\n" end test do w = "abc 123" w.word_wrap!(4) w.assert == "abc \n123\n" end end end facets-2.9.3/test/core/string/test_lchomp.rb0000644000004100000410000000043611714455226021117 0ustar www-datawww-datacovers 'facets/string/lchomp' test_case String do method :lchomp do test do s = "xxboo" r = s.lchomp("xx") r.assert == "boo" end end method :lchomp! do test do s = "xxboo" s.lchomp!("xx") s.assert == "boo" end end end facets-2.9.3/test/core/string/test_fold.rb0000644000004100000410000000075111714455226020561 0ustar www-datawww-datacovers 'facets/string/fold' test_case String do method :fold do test do s = "This is\na test.\n\nIt clumps\nlines of text." o = "This is a test.\n\nIt clumps lines of text." s.fold.assert == o end test "leave spaces" do s = "This is\na test.\n\n This is pre.\n Leave alone.\n\nIt clumps\nlines of text." o = "This is a test.\n\n This is pre.\n Leave alone.\n\nIt clumps lines of text." s.fold(true).assert == o end end end facets-2.9.3/test/core/string/test_splice.rb0000644000004100000410000000107611714455226021115 0ustar www-datawww-datacovers 'facets/string/splice' test_case String do method :splice do test do a = "HELLO" a.splice(1).assert == "E" a.assert == "HLLO" end test "range" do a = "HELLO" a.splice(1..2).assert == "EL" a.assert == "HLO" end test "store" do a = "HELLO" a.splice(1, "X") a.assert == "HXLLO" end end # This could be done if class of 2nd arg is checked. #method :splice_length # test do # a = "HELLO" # a.splice(1,2).assert == "EL" # a.assert == "HLO" # end #end end facets-2.9.3/test/core/string/test_to_re.rb0000644000004100000410000000111611714455226020741 0ustar www-datawww-datacovers 'facets/string/to_re' test_case String do method :to_re do test do "abc".to_re.assert == /abc/ "a+bc".to_re.assert == /a+bc/ "a+bc".to_re(false).assert == /a+bc/ "a+bc".to_re(true).assert == /a\+bc/ end end method :to_rx do test do "abc".to_rx.assert == /abc/ "a+bc".to_rx.assert == /a\+bc/ "a+bc".to_rx(false).assert == /a+bc/ "a+bc".to_rx(true).assert == /a\+bc/ end test "escaped characters" do a = "?" b = /#{a.to_rx}/ b.assert =~ "?" b.refute =~ "X" end end end facets-2.9.3/test/core/string/test_index_all.rb0000644000004100000410000000043211714455226021570 0ustar www-datawww-datacovers 'facets/string/index_all' test_case String do method :index_all do test "with string argument" do "axxxaxxxa".index_all('a').assert == [0,4,8] end test "with regexp argument" do "a123a567a9".index_all(/a/).assert == [0,4,8] end end end facets-2.9.3/test/core/string/test_each_word.rb0000644000004100000410000000035111714455226021564 0ustar www-datawww-datacovers 'facets/string/each_word.rb' test_case String do method :each_word do test do a = [] i = "this is a test" i.each_word{ |w| a << w } a.assert == ['this', 'is', 'a', 'test'] end end end facets-2.9.3/test/core/string/test_unquote.rb0000644000004100000410000000022311714455226021327 0ustar www-datawww-datacovers 'facets/string/unquote' test_case String do method :unquote do test do "'here'".unquote.assert == "here" end end end facets-2.9.3/test/core/string/test_cmp.rb0000644000004100000410000000044611714455226020415 0ustar www-datawww-datacovers 'facets/string/cmp' test_case String do method :cmp do test 'on strings' do "abc".cmp("abc").assert == 0 "abc".cmp("abcd").assert == -1 "abcd".cmp("abc").assert == 1 "abc".cmp("bcd").assert == -1 "bcd".cmp("abc").assert == 1 end end end facets-2.9.3/test/core/string/test_xor.rb0000644000004100000410000000033011714455226020436 0ustar www-datawww-datacovers 'facets/string/xor' test_case String do method :'^' do test do r = "try this out" ^ "puddingsnacks" x = "\004\a\035D\035\006\016\000N\016\026\037" r.assert == x end end end facets-2.9.3/test/core/string/test_capitalized.rb0000644000004100000410000000073111714455226022124 0ustar www-datawww-datacovers 'facets/string/capitalized' test_case String do method :capitalized? do test do 'Abc'.assert.capitalized? end end method :downcase? do test do 'abc'.assert.downcase? end end method :upcase? do test do 'ABC'.assert.upcase? end end #method :lowercase? do # test do # 'abc'.assert.lowercase? # end #end #method :uppercase? do # test do # 'ABC'.assert.uppercase? # end #end end facets-2.9.3/test/core/string/test_edit_distance.rb0000644000004100000410000000041511714455226022431 0ustar www-datawww-datacovers 'facets/string/edit_distance' test_case String do method :edit_distance do test do d = "pretzel".edit_distance('pretzil') d.assert = 1 end test do d = "zretzel".edit_distance('pretzil') d.assert = 2 end end end facets-2.9.3/test/core/string/test_subtract.rb0000644000004100000410000000035511714455226021464 0ustar www-datawww-datacovers 'facets/string/subtract' test_case String do method :- do test do ("foobar" - "oo").assert == "fbar" ("pizza pizza!" - "zz").assert == "pia pia!" ("letters" - /[a-z]+/).assert == "" end end end facets-2.9.3/test/core/string/test_margin.rb0000644000004100000410000000365111714455226021114 0ustar www-datawww-datacovers 'facets/string/margin' test_case String do method :margin do test do s = %q{ |ABC |123 |TEST }.margin s.assert == "ABC\n123\nTEST" end test do s = %q{ |ABC |123 |TEST }.margin s.assert == "ABC\n123\nTEST" end test do s = %q{|ABC |123 |TEST }.margin s.assert == "ABC\n123\nTEST" end test do s = %q{ |ABC |123 |TEST}.margin s.assert == "ABC\n123\nTEST" end test do s = %q{|ABC |123 |TEST}.margin s.assert == "ABC\n123\nTEST" end test do s = %q{ |ABC |123 |TEST}.margin s.assert == "ABC\n123\nTEST" end test do s = %q{ABC |123 |TEST }.margin s.assert == "ABC\n123\nTEST" end test "spacing" do s = %q{ | ABC | 123 | TEST }.margin s.assert == " ABC\n 123\n TEST" end test "spacing" do s = %q{ |ABC |123 |TEST }.margin(1) s.assert == " ABC\n 123\n TEST" end test "spacing" do s = %q{ |ABC |123 |TEST }.margin(2) s.assert == " ABC\n 123\n TEST" end test "spacing" do s = %q{ ABC - 123 - TEST }.margin s.assert == " ABC\n 123\n TEST" end test "random placement" do volly = {} 100.times{ |n| k = [] a = [] 5.times{ |i| k << ( ( ' ' * Integer(rand*10) ) + '|' + i.to_s ) a << ( i.to_s ) } volly[k.join("\n")] = a.join("\n") } volly.each{ |k,v| k.margin.assert == v } end end end facets-2.9.3/test/core/string/test_methodize.rb0000644000004100000410000000063411714455226021625 0ustar www-datawww-datacovers 'facets/string/methodize' test_case String do method :methodize do test "module name" do a = "FooBase" r = "foo_base" a.methodize.assert == r end test "path name" do a = "foo/base" r = "foo__base" a.methodize.assert == r end test "name space" do a = "Foo::Base" r = "foo__base" a.methodize.assert == r end end end facets-2.9.3/test/core/string/test_unbracket.rb0000644000004100000410000000103111714455226021603 0ustar www-datawww-datacovers 'facets/string/unbracket' test_case String do method :unbracket do test do s = "{unwrap me}" z = s.unbracket('{') z.assert == "unwrap me" end test do s = "--unwrap me!" z = s.unbracket('--','!') z.assert == "unwrap me" end end method :unbracket! do test do s = "{unwrap me}" s.unbracket!('{') s.assert == "unwrap me" end test do s = "--unwrap me!" s.unbracket!('--','!') s.assert == "unwrap me" end end end facets-2.9.3/test/core/string/test_store.rb0000644000004100000410000000025211714455226020765 0ustar www-datawww-datacovers 'facets/string/store' test_case String do method :store do test do a = "HELLO" a.store(1, "X") a.assert == "HXLLO" end end end facets-2.9.3/test/core/string/test_squish.rb0000644000004100000410000000066411714455226021154 0ustar www-datawww-datacovers 'facets/string/squish' test_case String do method :squish do test do r = %{ Multi-line string }.squish r.assert == "Multi-line string" end test do r = " foo bar \n \t boo".squish r.assert == "foo bar boo" end end method :squish! do test do s = " foo bar \n \t boo" s.squish! s.assert == "foo bar boo" end end end facets-2.9.3/test/core/string/test_snakecase.rb0000644000004100000410000000060711714455226021572 0ustar www-datawww-datacovers 'facets/string/snakecase' test_case String do method :snakecase do test 'dowcases' do 'URI'.snakecase.assert == 'uri' end test 'converts spaces' do 'MyStuff HisStuff'.snakecase.assert == 'my_stuff_his_stuff' end test 'does not alter path dividers' do '/my_module/my_class/'.snakecase.assert == '/my_module/my_class/' end end end facets-2.9.3/test/core/string/test_exclude.rb0000644000004100000410000000056711714455226021273 0ustar www-datawww-datacovers 'facets/string/exclude' test_case String do method :exclude? do test do "aaaa".assert.exclude?('bb') "aaab".assert.exclude?('bb') "aaba".assert.exclude?('bb') "baaa".assert.exclude?('bb') end test do "abba".refute.exclude?('bb') "aabb".refute.exclude?('bb') "bbaa".refute.exclude?('bb') end end end facets-2.9.3/test/core/string/test_rewrite.rb0000644000004100000410000000034211714455226021312 0ustar www-datawww-datacovers 'facets/string/rewrite' test_case String do method :rewrite do test do s = "HELLO TOMMY!" rules = [[ /TOMMY/, 'MAN' ]] r = s.rewrite(rules) r.assert == "HELLO MAN!" end end end facets-2.9.3/test/core/string/test_natcmp.rb0000644000004100000410000000063411714455226021117 0ustar www-datawww-datacovers 'facets/string/natcmp' test_case String do method :natcmp do test do "my_prog_v1.1.0".natcmp( "my_prog_v1.2.0").assert == -1 "my_prog_v1.2.0".natcmp("my_prog_v1.10.0").assert == -1 "my_prog_v1.2.0".natcmp( "my_prog_v1.1.0").assert == 1 "my_prog_v1.10.0".natcmp("my_prog_v1.2.0").assert == 1 "my_prog_v1.0.0".natcmp( "my_prog_v1.0.0").assert == 0 end end end facets-2.9.3/test/core/string/test_tab.rb0000644000004100000410000000030211714455226020373 0ustar www-datawww-datacovers 'facets/string/tab' test_case String do # TODO: Need to expand on #tab tests. method :tab do test do a = "xyz".tab(4) a[0..3].assert == ' ' end end end facets-2.9.3/test/core/string/test_indent.rb0000644000004100000410000000403111714455226021111 0ustar www-datawww-datacovers 'facets/string/indent' test_case String do method :indent do test "positive" do "xyz".indent(4).assert == ' xyz' " xyz".indent(2).assert == ' xyz' end test "multiline positive" do "abc\nxyz".indent(2).assert == " abc\n xyz" end test "zero" do 'xyz'.indent(0).assert == 'xyz' end test "negative" do ' xyz'.indent(-2).assert == ' xyz' ' xyz'. indent(-2).assert == 'xyz' end test "multiline negative" do " abc\n xyz".indent(-2).assert == " abc\n xyz" end test "negative more than is possible" do ' xyz'.indent(-3).assert == 'xyz' end test "non-space positive" do "xyz".indent(4, '-').assert == '----xyz' end test "non-space zero" do 'xyz'.indent(0, '-').assert == 'xyz' end test "non-space negative non-matching character" do ' xyz'.indent(-2, '-').assert == ' xyz' ' xyz'. indent(-2, '-').assert == ' xyz' end test "non-space negative" do '----xyz'.indent(-2, '-').assert == '--xyz' '--xyz'.indent(-2, '-').assert == 'xyz' end Concern "Special regular expresion characters are escaped." test "ensure '.' is treated literally and not as wildcard" do ' xyz'.indent(-2, '.').assert == ' xyz' '..xyz'.indent(-2, '.').assert == 'xyz' end test "ensure '*' is treated literally and not as wildcard" do ' xyz'.indent(-2, '*').assert == ' xyz' '**xyz'.indent(-2, '*').assert == 'xyz' end test "ensure '^' is treated literally and not as line start" do ' xyz'.indent(-2, '^').assert == ' xyz' '^^xyz'.indent(-2, '^').assert == 'xyz' end end method :indent! do test "in place rendition of #unindent" do s = "xyz" s.indent!(4) s.assert == ' xyz' s = " xyz" s.indent!(2) s.assert == ' xyz' end end #method :unindent do # test "is an alias for negative indent" do # ' xyz'.unindent(2).assert == 'xyz' # end #end end facets-2.9.3/test/core/string/test_nchar.rb0000644000004100000410000000043211714455226020724 0ustar www-datawww-datacovers 'facets/string/nchar' test_case String do method :nchar do test do "abcxyz".nchar(3).assert == "abc" "abcxyz".nchar(-3).assert == "xyz" "abcxyz".nchar(3, 'HI').assert == "HIxyz" "abcxyz".nchar(-3, 'HI').assert == "abcHI" end end end facets-2.9.3/test/core/string/test_variablize.rb0000644000004100000410000000024211714455226021760 0ustar www-datawww-datacovers 'facets/string/variablize' test_case String do method :variablize do test do s = "a" s.variablize.assert == "@a" end end end facets-2.9.3/test/core/string/test_cleanlines.rb0000644000004100000410000000025311714455226021747 0ustar www-datawww-datacovers 'facets/string/cleanlines' test_case String do method :cleanlines do test do "a \n b \nc".cleanlines.to_a.assert == ["a","b","c"] end end end facets-2.9.3/test/core/string/test_line_wrap.rb0000644000004100000410000000033011714455226021606 0ustar www-datawww-datacovers 'facets/string/line_wrap' test_case String do method :line_wrap do test do "abc123".line_wrap(3).assert == "abc\n123\n" "abcd123".line_wrap(4).assert == "abcd\n123\n" end end end facets-2.9.3/test/core/string/test_unindent.rb0000644000004100000410000000436411714455226021465 0ustar www-datawww-datacovers 'facets/string/unindent' test_case String do method :unindent do Concern "Single-line indentation" test "removes space indentation" do "\s\sabc".unindent.assert == "abc" end test "removes_tab_indentation" do "\tabc".unindent.assert == "abc" end test "removes space and tab indentation" do "\t\sabc".unindent.assert == "abc" end Concern "Multi-line indentation" test "removes indentation" do "\tabc\n\tabc".unindent.assert == "abc\nabc" end test "keeps relative indentation" do "\tabc\n\t\tabc".unindent.assert == "abc\n\tabc" end test "ignores blank lines for indent calculation" do "\n\tabc\n\n\t\tabc\n".unindent.assert == "\nabc\n\n\tabc\n" end Concern "Complex examples" ex1 = <<-EOF I must go down to the seas again The lonely sea and the sky And all I want is a tall ship And a star to steer her by EOF ex2 = <<-EOF "Eek!" She cried As the mouse quietly scurried by. EOF test "simple examples" do " xyz".unindent(-1).assert == " xyz" " xyz".unindent(0).assert == " xyz" " xyz".unindent(1).assert == " xyz" " xyz".unindent(2).assert == " xyz" " xyz".unindent(3).assert == "xyz" " xyz".unindent(4).assert == "xyz" end test "large example unindented one space" do expected = <<-EOF I must go down to the seas again The lonely sea and the sky And all I want is a tall ship And a star to steer her by EOF actual = ex1.unindent(1) actual.assert == expected end test "large example unindented four spaces" do expected = <<-EOF I must go down to the seas again The lonely sea and the sky And all I want is a tall ship And a star to steer her by EOF actual = ex1.unindent(4) actual.assert == expected end test "unindent larger than current indention" do expected = <<-EOF "Eek!" She cried As the mouse quietly scurried by. EOF actual = ex2.unindent(100) actual.assert == expected end end method :unindent! do test "modifies string in place" do str = "\s\sabc" str.unindent! str.assert == "abc" end end end facets-2.9.3/test/core/string/test_bracket.rb0000644000004100000410000000150411714455226021245 0ustar www-datawww-datacovers 'facets/string/bracket' test_case String do method :bracket do test do 'X'.bracket('#').assert == '#X#' 'X'.bracket('x','!').assert == 'xX!' 'X'.bracket('{','}').assert == '{X}' 'X'.bracket('<').assert == '' 'X'.bracket('(').assert == '(X)' 'X'.bracket('[').assert == '[X]' 'X'.bracket('{').assert == '{X}' end end method :bracket! do test do a = 'X' ; a.bracket!('#') a.assert == '#X#' a = 'X' ; a.bracket!('x','!') a.assert == 'xX!' a = 'X' ; a.bracket!('{','}') a.assert == '{X}' a = 'X' ; a.bracket!('<') a.assert == '' a = 'X' ; a.bracket!('(') a.assert == '(X)' a = 'X' ; a.bracket!('[') a.assert == '[X]' a = 'X' ; a.bracket!('{') a.assert == '{X}' end end end facets-2.9.3/test/core/string/test_titlecase.rb0000644000004100000410000000030011714455226021600 0ustar www-datawww-datacovers 'facets/string/titlecase' test_case String do method :titlecase do test do r = "try this out".titlecase x = "Try This Out" r.assert == x end end end facets-2.9.3/test/core/string/test_modulize.rb0000644000004100000410000000063011714455226021461 0ustar www-datawww-datacovers 'facets/string/modulize' test_case String do method :modulize do test "snakecase" do a = "foo_bar" r = "FooBar" a.modulize.assert == r end test "path name" do a = "foo/bar" r = "Foo::Bar" a.modulize.assert == r end test "on methodized string" do a = "foo__bar" r = "Foo::Bar" a.modulize.assert == r end end end facets-2.9.3/test/core/string/test_expand_tabs.rb0000644000004100000410000000262311714455226022125 0ustar www-datawww-datacovers 'facets/string/expand_tab' test_case String do setup do @tabs = <<-EOF \tOne tab \tOne space and one tab \t Six spaces, a tab, and a space EOF end method :expand_tabs do test "0" do expected = <<-EOF One tab One space and one tab Six spaces, a tab, and a space EOF @tabs.expand_tabs(0).assert == expected end test "1" do expected = <<-EOF One tab One space and one tab Six spaces, a tab, and a space EOF @tabs.expand_tabs(1).assert == expected end test "4" do expected = <<-EOF One tab One space and one tab Six spaces, a tab, and a space EOF @tabs.expand_tabs(4).assert == expected end test "8" do expected = <<-EOF One tab One space and one tab Six spaces, a tab, and a space EOF @tabs.expand_tabs.assert == expected @tabs.expand_tabs(8).assert == expected end test "16" do expected = <<-EOF One tab One space and one tab Six spaces, a tab, and a space EOF @tabs.expand_tabs(16).assert == expected end end method :expand_tab do test "0 (alias for #expand_tabs)" do expected = <<-EOF One tab One space and one tab Six spaces, a tab, and a space EOF @tabs.expand_tab(0).assert == expected end end end facets-2.9.3/test/core/string/test_lines.rb0000644000004100000410000000033211714455226020742 0ustar www-datawww-datacovers 'facets/string/lines' test_case String do # Ruby 1.9 defined #lines to keep the newline character. method :lines do test do "a\nb\nc".lines.to_a.assert == ["a\n","b\n","c"] end end end facets-2.9.3/test/core/string/test_shatter.rb0000644000004100000410000000041111714455226021300 0ustar www-datawww-datacovers 'facets/string/shatter' test_case String do method :shatter do test do s = "

Thisisa test.

" r = s.shatter( /<.*?>/ ) x = ["

", "This", "", "is", "", "a test.", "

"] r.assert == x end end end facets-2.9.3/test/core/string/test_start_with.rb0000644000004100000410000000042111714455226022017 0ustar www-datawww-datacovers 'facets/string/start_with' test_case String do method :start_with? do test do s = "xxboo" s.assert.start_with?('xx') end end method :starts_with? do test do s = "xxboo" s.assert.starts_with?('xx') end end end facets-2.9.3/test/core/string/test_newlines.rb0000644000004100000410000000042411714455226021456 0ustar www-datawww-datacovers 'facets/string/newlines' test_case String do # Since Ruby 1.9 defined #lines to keep the newline character, # we have defined #newlines to leave them out. method :newlines do test do "a\nb\nc".newlines.to_a.assert == ["a","b","c"] end end end facets-2.9.3/test/core/string/test_characters.rb0000644000004100000410000000032511714455226021751 0ustar www-datawww-datacovers 'facets/string/characters' test_case String do method :characters do test do "abc".characters.assert == ["a","b","c"] "ab\nc".characters.assert == ["a","b","\n","c"] end end end facets-2.9.3/test/core/string/test_end_with.rb0000644000004100000410000000041311714455226021431 0ustar www-datawww-datacovers 'facets/string/end_with' test_case String do method :end_with? do test do s = "xxboo" s.assert.end_with?('boo') end end method :ends_with? do test do s = "xxboo" s.assert.ends_with?('boo') end end end facets-2.9.3/test/core/string/test_file.rb0000644000004100000410000000031211714455226020545 0ustar www-datawww-datacovers 'facets/string/file' test_case String do method :file do test do "home/trans".file.dirname.assert == "home" "home/trans".file.basename.assert == "trans" end end end facets-2.9.3/test/core/string/test_camelcase.rb0000644000004100000410000000310611714455226021547 0ustar www-datawww-datacovers 'facets/string/camelcase' test_case String do method :camelcase do test do "Camel_case".camelcase.assert == "CamelCase" end test "converts underscore to captialized" do "abc_xyz".camelcase.assert == "abcXyz" "abc____xyz".camelcase.assert == "abcXyz" end test "can captialize at spaces" do "abc xyz".camelcase(' ').assert == "abcXyz" "abc xyz".camelcase(' ').assert == "abcXyz" end test "can capitalize at arbitrary string" do "abc;xyz".camelcase(';').assert == "abcXyz" "abc//xyz".camelcase('//').assert == "abcXyz" end test "can captialize at regexp" do "abc\nxyz".camelcase(/\s/).assert == "abcXyz" "abc\txyz".camelcase(/\s/).assert == "abcXyz" end # this functionality is in String#modulize instead test "does not convert paths to module names" do 'my_module/my_class'.camelcase.refute == 'MyModule::MyClass' '/my_module/my_class'.camelcase.refute == '::MyModule::MyClass' end # this functionality is in String#modulize instead test "does not convert methods to module names" do 'My_module__my_class'.camelcase.refute == 'MyModule::MyClass' '__My_module__my_class'.camelcase.refute == '::MyModule::MyClass' end end method :lower_camelcase do test do "abc_xyz".lower_camelcase.assert == "abcXyz" "Abc_xyz".lower_camelcase.assert == "abcXyz" end end method :upper_camelcase do test do "abc_xyz".upper_camelcase.assert == "AbcXyz" "Abc_xyz".upper_camelcase.assert == "AbcXyz" end end end facets-2.9.3/test/core/string/test_cleave.rb0000644000004100000410000000220511714455226021070 0ustar www-datawww-datacovers 'facets/string/cleave' test_case String do method :cleave do table = [ [ 'no spaces short word' , 'whole' , ['whole', ''] ], [ 'no spaces long word' , 'Supercalifragilisticexpialidocious' , ['Supercalifragilisticexpialidocious', ''] ], [ 'exact middle two words' , 'fancy split' , ['fancy', 'split'] ], [ 'exact middle many words' , 'All good Rubyists know how to party', ['All good Rubyists', 'know how to party'] ], [ 'closer to start' , 'short splitter' , ['short', 'splitter'] ], [ 'closer to start' , 'Four score and seven years ago...' , ['Four score and', 'seven years ago...'] ], [ 'closer to start' , 'abc def ghijklm nop' , ['abc def', 'ghijklm nop'] ], [ 'closer to end' , 'extended split' , ['extended', 'split'] ], [ 'closer to end' , 'abc defghi jklm nop' , [ 'abc defghi', 'jklm nop'] ] ] table.each do |d, s, x| test d do s.cleave.assert == x end end end end facets-2.9.3/test/core/string/test_pathize.rb0000644000004100000410000000076711714455226021310 0ustar www-datawww-datacovers 'facets/string/pathize' test_case String do method :pathize do test "module name" do a = "Foo::Base" x = "foo/base" a.pathize.assert == x end test "path name" do a = "foo/base" x = "foo/base" a.pathize.assert == x end test "name space" do a = "foo__base" x = "foo/base" a.pathize.assert == x end test 'transforms initial double colon' do '::MyClass'.pathize.assert == '/my_class' end end end facets-2.9.3/test/core/string/test_underscore.rb0000644000004100000410000000056211714455226022006 0ustar www-datawww-datacovers 'facets/string/underscore' test_case String do method :underscore do test "from camelcase" do "SnakeCase".underscore.assert == "snake_case" end test "containing a dash" do "Snake-Case".underscore.assert == "snake_case" end test "containing spaces" do "Snake Case".underscore.assert == "snake_case" end end end facets-2.9.3/test/core/string/test_lowercase.rb0000644000004100000410000000032111714455226021612 0ustar www-datawww-datacovers 'facets/string/lowercase' test_case String do method :lowercase do test do "Bob".lowercase.assert == "bob" end test do "BOB".lowercase.assert == "bOB" end end end facets-2.9.3/test/core/string/test_unfold.rb0000644000004100000410000000040011714455226021113 0ustar www-datawww-datacovers 'facets/string/unfold' test_case String do method :unfold do test do str = "This is a test of\nparagraph folding." res = str.unfold exp = "This is a test of paragraph folding." res.assert == exp end end end facets-2.9.3/test/core/string/test_quote.rb0000644000004100000410000000155411714455226020774 0ustar www-datawww-datacovers 'facets/string/quote' test_case String do method :quote do test "counting quotes" do 'hi'.quote(1).assert == %{'hi'} 'hi'.quote(2).assert == %{"hi"} 'hi'.quote(3).assert == %{'"hi"'} 'hi'.quote(4).assert == %{""hi""} 'hi'.quote(5).assert == %{'""hi""'} end test "default double quotes" do 'hi'.quote.assert == %{"hi"} end test "single quotes" do 'hi'.quote(:s).assert == %{'hi'} 'hi'.quote(:single).assert == %{'hi'} end test "double quotes" do 'hi'.quote(:d).assert == %{"hi"} 'hi'.quote(:double).assert == %{"hi"} end test "back quotes" do 'hi'.quote(:b).assert == %{`hi`} 'hi'.quote(:back).assert == %{`hi`} end test "bracket quotes" do 'hi'.quote(:sb).assert == "`hi'" 'hi'.quote(:bracket).assert == "`hi'" end end end facets-2.9.3/test/core/string/test_each_char.rb0000644000004100000410000000032511714455226021527 0ustar www-datawww-datacovers 'facets/string/each_char' test_case String do method :each_char do test do a = [] i = "this" i.each_char{ |w| a << w } a.assert == ['t', 'h', 'i', 's'] end end end facets-2.9.3/test/core/string/test_words.rb0000644000004100000410000000053411714455226020772 0ustar www-datawww-datacovers 'facets/string/words' test_case String do method :words do test do x = "a b c\nd e" x.words.assert == ['a','b','c','d','e'] end test do x = "ab cd\nef" x.words.assert == ['ab','cd','ef'] end test do x = "ab cd \n ef-gh" x.words.assert == ['ab','cd','ef-gh'] end end end facets-2.9.3/test/core/string/test_tabto.rb0000644000004100000410000000030611714455226020742 0ustar www-datawww-datacovers 'facets/string/tabto' test_case String do # TODO: Need to expand tabto tests method :tabto do test do a = "xyz".tabto(4) a[0..3].assert == ' ' end end end facets-2.9.3/test/core/string/test_align.rb0000644000004100000410000000104011714455226020717 0ustar www-datawww-datacovers 'facets/string/align' test_case String do method :align do test do "xxx".align(:right, 9) == " xxx" "xxx".align(:left, 9).assert == "xxx " "xxx".align(:center, 9).assert == " xxx " end end method :align_right do test do "xxx".align_right(9) == " xxx" end end method :align_left do test do "xxx".align_left(9).assert == "xxx " end end method :align_center do test do "xxx".align_center(9).assert == " xxx " end end end facets-2.9.3/test/core/string/test_similarity.rb0000644000004100000410000000025411714455226022021 0ustar www-datawww-datacovers 'facets/string/similarity' test_case String do method :similarity do test do "Alexsander".similarity("Aleksander").assert == 0.9 end end end facets-2.9.3/test/core/string/test_mscan.rb0000644000004100000410000000042411714455226020733 0ustar www-datawww-datacovers 'facets/string/mscan' test_case String do method :mscan do test do r = 'abc,def,gh'.mscan(/[,]/) assert( r.all?{ |md| MatchData === md } ) r.to_a.length.assert == 2 r[0][0].assert == ',' r[1][0].assert == ',' end end end facets-2.9.3/test/core/string/test_divide.rb0000644000004100000410000000037211714455226021100 0ustar www-datawww-datacovers 'facets/string/divide' test_case String do method :divide do test do s = "

Thisisa test.

" d = s.divide( /<.*?>/ ) e = ["

This", "is", "a test.", "

"] d.assert == e end end end facets-2.9.3/test/core/string/test_range.rb0000644000004100000410000000104211714455226020723 0ustar www-datawww-datacovers 'facets/string/range' test_case String do method :range do test do "a123a567a9".range(/123/).assert == (1..3) "a123a567a9".range(/a/).assert == (0..0) end end method :range_all do test do "a123a123a9".range_all(/123/).assert == [ (1..3), (5..7) ] "a123a567a9".range_all(/a/).assert == [ (0..0), (4..4), (8..8) ] end end method :range_of_line do test do a = "0123\n456\n78" x = [0..4, 5..8, 9..10] r = a.range_of_line r.assert == x end end end facets-2.9.3/test/core/string/test_uppercase.rb0000644000004100000410000000041411714455226021620 0ustar www-datawww-datacovers 'facets/string/uppercase' test_case String do method :uppercase do test do "bob".uppercase.assert == "Bob" end test do "boB".uppercase.assert == "BoB" end test do "BoB".uppercase.assert == "BoB" end end end facets-2.9.3/test/core/string/test_op_sub.rb0000644000004100000410000000024211714455226021117 0ustar www-datawww-datacovers 'facets/string/op_sub' test_case String do method :"-" do test do s = "xxbooxxfoo" (s - "xx").assert == "boofoo" end end end facets-2.9.3/test/core/string/test_op_div.rb0000644000004100000410000000031011714455226021104 0ustar www-datawww-datacovers 'facets/string/op_div' test_case String do method :/ do test do ('merb' / 'string').assert == "merb/string" ('merb' / :symbol).assert == "merb/symbol" end end end facets-2.9.3/test/core/symbol/0000755000004100000410000000000011714455226016245 5ustar www-datawww-datafacets-2.9.3/test/core/symbol/test_to_proc.rb0000644000004100000410000000123311714455226021275 0ustar www-datawww-datacovers 'facets/symbol/to_proc' test_case Symbol do method :to_proc do test do x = (1..10).inject(&:*) x.assert == 3628800 x = %w{foo bar qux}.map(&:reverse) x.assert == %w{oof rab xuq} x = [1, 2, nil, 3, nil].reject(&:nil?) x.assert == [1, 2, 3] x = %w{ruby and world}.sort_by(&:reverse) x.assert == %w{world and ruby} end test "call" do up = :upcase.to_proc up.assert.is_a?(Proc) up.call("hello").assert == "HELLO" end test "map" do q = [[1,2,3], [4,5,6], [7,8,9]].map(&:reverse) a = [[3, 2, 1], [6, 5, 4], [9, 8, 7]] q.assert == a end end end facets-2.9.3/test/core/symbol/test_as_s.rb0000644000004100000410000000023611714455226020557 0ustar www-datawww-datacovers 'facets/symbol/as_s' test_case Symbol do method :as_s do test do s = :foo.as_s.sub('f','g') s.assert == :goo end end end facets-2.9.3/test/core/symbol/test_not.rb0000644000004100000410000000033011714455226020425 0ustar www-datawww-datacovers 'facets/symbol/not' test_case Symbol do method :~@ do test do ~:a.assert == :"~a" end end method :not? do test do a = :a n = ~a assert( n.not? ) end end end facets-2.9.3/test/core/symbol/test_chomp.rb0000644000004100000410000000033311714455226020736 0ustar www-datawww-datacovers 'facets/symbol/chomp' test_case Symbol do method :chomp do test do :ab.chomp(:b).assert == :a end end method :lchomp do test do :ab.lchomp(:a).assert == :b end end end facets-2.9.3/test/core/symbol/test_bang.rb0000644000004100000410000000025211714455226020537 0ustar www-datawww-datacovers 'facets/symbol/bang' test_case Symbol do method :bang? do test do :a.refute.bang? :a?.refute.bang? :a!.assert.bang? end end end facets-2.9.3/test/core/symbol/test_generate.rb0000644000004100000410000000060111714455226021420 0ustar www-datawww-datacovers 'facets/symbol/generate' test_case Symbol do class_method :generate do test "without key" do Symbol.generate.assert == :'-1' Symbol.generate.assert == :'-2' end end class_method :generate do test "with prefix key" do Symbol.generate('orange').assert == :'orange-1' Symbol.generate('orange').assert == :'orange-2' end end end facets-2.9.3/test/core/symbol/test_plain.rb0000644000004100000410000000033011714455226020730 0ustar www-datawww-datacovers 'facets/symbol/plain' test_case Symbol do method :plain? do test do assert( :try.plain? ) end test do assert( ! :try=.plain? ) assert( ! :try?.plain? ) end end end facets-2.9.3/test/core/symbol/test_variablize.rb0000644000004100000410000000023411714455226021760 0ustar www-datawww-datacovers 'facets/symbol/variablize' test_case Symbol do method :variablize do test do :a.variablize.assert == "@a".to_sym end end end facets-2.9.3/test/core/symbol/test_setter.rb0000644000004100000410000000033311714455226021136 0ustar www-datawww-datacovers 'facets/symbol/setter' test_case Symbol do method :setter? do test do assert( :try=.setter? ) end test do assert( ! :try.setter? ) assert( ! :try?.setter? ) end end end facets-2.9.3/test/core/symbol/test_query.rb0000644000004100000410000000033011714455226020772 0ustar www-datawww-datacovers 'facets/symbol/query' test_case Symbol do method :query? do test do assert( :try?.query? ) end test do assert( ! :try.query? ) assert( ! :try=.query? ) end end end facets-2.9.3/test/core/symbol/test_succ.rb0000644000004100000410000000027711714455226020574 0ustar www-datawww-datacovers 'facets/symbol/succ' test_case Symbol do method :succ do test do :a.succ.assert == :b :aaa.succ.assert == :aab :"1".succ.assert == :"2" end end end facets-2.9.3/test/core/symbol/test_op_div.rb0000644000004100000410000000030611714455226021110 0ustar www-datawww-datacovers 'facets/symbol/op_div' test_case Symbol do method :/ do test do (:merb / "string").assert == "merb/string" (:merb / :symbol).assert == "merb/symbol" end end end facets-2.9.3/test/core/enumerator_tc.rb0000644000004100000410000000106011714455226020131 0ustar www-datawww-datacovers 'facets/enumerator' test_case Enumerator::Yielder do class_method :new do test do y = Enumerator::Yielder.new{ |x| x + 1 } end end method :yield do test do y = Enumerator::Yielder.new{ |x| x + 1 } y.yield(1).assert == 2 end end method :<< do test do a = [] y = Enumerator::Yielder.new{ |x| a << x + 1 } y << 1 a.assert == [2] end test do a = [] y = Enumerator::Yielder.new{ |x,y| a << x + y } y.<<(1,2) a.assert == [3] end end end facets-2.9.3/test/core/proc/0000755000004100000410000000000011714455226015703 5ustar www-datawww-datafacets-2.9.3/test/core/proc/test_partial.rb0000644000004100000410000000072611714455226020730 0ustar www-datawww-datacovers 'facets/proc/partial' test_case Proc do method :partial do test "first argument" do f = Proc.new{ |a,b,c| a + b + c } n = f.partial(NA,2,3) n[1].assert == 6 end test "second argument" do f = Proc.new{ |a,b,c| a + b + c } n = f.partial(1,NA,3) n[2].assert == 6 end test "third argument" do f = Proc.new{ |a,b,c| a + b + c } n = f.partial(1,2,NA) n[3].assert == 6 end end end facets-2.9.3/test/core/proc/test_curry.rb0000644000004100000410000000132711714455226020436 0ustar www-datawww-datacovers 'facets/proc/curry' test_case Proc do method :curry do test do f = Proc.new{ |a,b,c| a + b + c } c = f.curry c[1][2][3].assert == 6 end test "with arguments" do f = Proc.new{ |a,b| a**b } c = f.curry(0) c[2][3].assert == 8 f = Proc.new{ |a,b| a**b } c = f.curry(1) c[2][3].assert == 9 end test "with in class scope" do # first test the lambda org = lambda{ |y, x| x + " " + y } foo = org.curry['yeah'] foo['boo'].assert == 'boo yeah' # now test it as a method definition baz = Class.new baz.__send__(:define_method, 'foo', foo) baz.new.foo('boo').assert == 'boo yeah' end end end facets-2.9.3/test/core/proc/test_compose.rb0000644000004100000410000000064511714455226020741 0ustar www-datawww-datacovers 'facets/proc/compose' test_case Proc do method :compose do test do a = lambda { |x| x + 4 } b = lambda { |y| y / 2 } (a.compose(b)).call(4).assert == 6 (b.compose(a)).call(4).assert == 4 end end method :* do test do a = lambda { |x| x + 4 } b = lambda { |y| y / 2 } (a * b).call(4).assert == 6 (b * a).call(4).assert == 4 end end end facets-2.9.3/test/core/proc/test_to_method.rb0000644000004100000410000000140411714455226021250 0ustar www-datawww-datacovers 'facets/proc/to_method' test_case Proc do method :to_method do test do o = Object.new tproc = proc { |x| x + 2 } tmeth = tproc.to_method(o, :tryit) tmeth.call(1).assert == 3 o.assert.respond_to?(:tryit) o.tryit(1).assert == 3 end test "with immutable object" do o = :foo tproc = proc{ self } tmeth = tproc.to_method(o, :tryit) tmeth.call.assert == :foo o.assert.respond_to?(:tryit) o.tryit.assert == :foo end test "ensure method is in object scope" do o = Struct.new(:a).new(1) tproc = proc{ a } tmeth = tproc.to_method(o, :tryit) tmeth.call.assert == 1 o.assert.respond_to?(:tryit) o.tryit.assert == 1 end end end facets-2.9.3/test/core/proc/test_update.rb0000644000004100000410000000024511714455226020552 0ustar www-datawww-datacovers 'facets/proc/update' test_case Proc do method :update do test do p1 = Proc.new{ 'here' } p1.update.assert == 'here' end end end facets-2.9.3/test/core/proc/test_bind_to.rb0000644000004100000410000000033011714455226020701 0ustar www-datawww-datacovers 'facets/proc/bind_to' test_case Proc do method :bind_to do test do a = [1,2,3] p1 = Proc.new{ join(' ') } p2 = p1.bind_to(a) p2.call.assert == '1 2 3' end end end facets-2.9.3/test/core/proc/test_bind.rb0000644000004100000410000000121611714455226020203 0ustar www-datawww-datacovers 'facets/proc/bind' test_case Proc do # Not sure why this is thread critical? method :bind do test "thread critial" do a = 2 tproc = lambda { |x| x + a } 99.times { tmethod = tproc.bind(self) #to_method tmethod.call(1).assert == 3 } meths = ( Object.instance_methods + Object.public_instance_methods + Object.private_instance_methods + Object.protected_instance_methods ) meths = meths.select{ |s| s.to_s =~ /^_bind_/ } #meths = Symbol.all_symbols.select { |s| s.to_s =~ /^_bind_/ } # why? meths.size.assert == 0 end end end facets-2.9.3/test/core/hash/0000755000004100000410000000000011714455226015663 5ustar www-datawww-datafacets-2.9.3/test/core/hash/test_new_with.rb0000644000004100000410000000032611714455226021074 0ustar www-datawww-datacovers 'facets/hash/new_with' test_case Hash do class_method :new_with do test do h = Hash.new_with{0} h[:ab].assert == 0 h[100].assert == 0 h["a"].assert == 0 end end end facets-2.9.3/test/core/hash/test_delete_values.rb0000644000004100000410000000071611714455226022074 0ustar www-datawww-datacovers 'facets/hash/delete_values' test_case Hash do method :delete_values do test do a = { :a => 1, :b => 2, :c => 3 } x = { :b => 2, :c => 3 } r = a.delete_values(1) #r.assert == x a.assert == x end end method :delete_values_at do test do a = { :a => 1, :b => 2, :c => 3 } x = { :b => 2, :c => 3 } r = a.delete_values_at(:a) r.assert == [1] a.assert == x end end end facets-2.9.3/test/core/hash/test_to_proc.rb0000644000004100000410000000037111714455226020715 0ustar www-datawww-datacovers 'facets/hash/to_proc' test_case Hash do method :to_proc do test do c = Class.new do attr_accessor :a end h = {:a => 1} o = c.new h.to_proc.call(o) o.a.assert == 1 end end end facets-2.9.3/test/core/hash/test_symbolize_keys.rb0000644000004100000410000000063511714455226022323 0ustar www-datawww-datacovers 'facets/hash/symbolize_keys' test_case Hash do method :symbolize_keys do test do foo = { 'a'=>1, 'b'=>2 } foo.symbolize_keys == { :a=>1, :b=>2 } foo.assert == { "a" =>1, "b"=>2 } end end method :symbolize_keys! do test do foo = { 'a'=>1, 'b'=>2 } foo.symbolize_keys!.assert == { :a=>1, :b=>2 } foo.assert == { :a=>1, :b=>2 } end end end facets-2.9.3/test/core/hash/test_join.rb0000644000004100000410000000072511714455226020212 0ustar www-datawww-datacovers 'facets/hash/join' test_case Hash do method :join do setup do @h = {:a=>1, :b=>2} end test do s = @h.join s.assert.include?('b2') s.assert.include?('a1') end test do s = @h.join(',') s.assert.include?('a,1') s.assert.include?('b,2') end test do s = @h.join(',', ':') s.assert.include?('a,1') s.assert.include?('b,2') s.assert.include?(':') end end end facets-2.9.3/test/core/hash/test_keys.rb0000644000004100000410000000152311714455226020223 0ustar www-datawww-datacovers 'facets/hash/keys' test_case Hash do method :each_with_key do test do h1 = {:a=>1, :b=>2} h2 = {} h1.each_with_key { |v,k| h2[v] = k } h2.assert == {1=>:a, 2=>:b} end end method :keys? do test do {:a=>1,:b=>2,:c=>3}.assert.keys?(:a,:b) {:a=>1,:b=>2,:c=>3 }.refute.keys?(:a,:b,:d) end end method :only_keys? do test do {:a=>1,:b=>2,:c=>3}.assert.only_keys?(:a,:b,:c) {:a=>1,:b=>2,:c=>3}.refute.only_keys?(:a,:b) end end method :has_keys? do test do {:a=>1,:b=>2,:c=>3}.assert.has_keys?(:a,:b) {:a=>1,:b=>2,:c=>3 }.refute.has_keys?(:a,:b,:d) end end method :has_only_keys? do test do {:a=>1,:b=>2,:c=>3}.assert.has_only_keys?(:a,:b,:c) {:a=>1,:b=>2,:c=>3}.refute.has_only_keys?(:a,:b) end end end facets-2.9.3/test/core/hash/test_autonew.rb0000644000004100000410000000055111714455226020732 0ustar www-datawww-datacovers 'facets/hash/autonew' test_case Hash do class_method :autonew do test do h = Hash.autonew h['s1']['p1'] = 4 h['s1']['p2'] = 5 h['s1']['p3'] = 2 h['s1']['p4'] = 3 h.assert == {"s1"=>{"p1"=>4, "p4"=>3, "p3"=>2, "p2"=>5}} h['s1'].keys.sort.assert == ["p1", "p2", "p3", "p4"] end end end facets-2.9.3/test/core/hash/test_stringify_keys.rb0000644000004100000410000000064411714455226022324 0ustar www-datawww-datacovers 'facets/hash/stringify_keys' test_case Hash do method :stringify_keys do test do foo = { :a=>1, :b=>2 } foo.stringify_keys.assert == { "a"=>1, "b"=>2 } foo.assert == { :a =>1, :b=>2 } end end method :stringify_keys! do test do foo = { :a=>1, :b=>2 } foo.stringify_keys!.assert == { "a"=>1, "b"=>2 } foo.assert == { "a"=>1, "b"=>2 } end end end facets-2.9.3/test/core/hash/test_traverse.rb0000644000004100000410000000072511714455226021106 0ustar www-datawww-datacovers 'facets/hash/traverse' test_case Hash do method :traverse do test do h = { "A" => "x", "B" => "y" } j = h.traverse{ |k,v| [k.downcase, v.upcase] } x = { "a" => "X", "b" => "Y" } j.refute == h j.assert == x end end method :traverse! do test do h = { "A" => "x", "B" => "y" } h.traverse!{ |k,v| [k.downcase, v.upcase] } x = { "a" => "X", "b" => "Y" } h.assert == x end end end facets-2.9.3/test/core/hash/test_update_values.rb0000644000004100000410000000034111714455226022106 0ustar www-datawww-datacovers 'facets/hash/update_values' test_case Hash do method :update_values do test do h = {1 => 'A', 2 => 'B'} h.update_values{ |v| v.downcase } h.assert == {1 => 'a', 2 => 'b'} end end end facets-2.9.3/test/core/hash/test_delete_unless.rb0000644000004100000410000000040211714455226022076 0ustar www-datawww-datacovers 'facets/hash/delete_unless' test_case Hash do method :delete_unless do test do a = { :a => 1, :b => 2, :c => 3 } x = { :a => 1 } r = a.delete_unless{|k,v| v == 1} r.assert == x a.assert == x end end end facets-2.9.3/test/core/hash/test_op_add.rb0000644000004100000410000000035211714455226020475 0ustar www-datawww-datacovers 'facets/hash/op_add' test_case Hash do method :+ do test do a = { :a => 1, :b => 2 } b = { :b => 3, :c => 4 } x = { :a => 1, :b => 3, :c => 4 } r = a + b r.assert == x end end end facets-2.9.3/test/core/hash/test_update_each.rb0000644000004100000410000000037511714455226021516 0ustar www-datawww-datacovers 'facets/hash/update_each' test_case Hash do method :update_each do test do a = { :a => 1, :b => 2, :c => 3 } x = { :a => 2, :b => 3, :c => 4 } a.update_each{ |k,v| { k => v+1 } } a.assert == x end end end facets-2.9.3/test/core/hash/test_recurse.rb0000644000004100000410000000160311714455226020717 0ustar www-datawww-datacovers 'facets/hash/recurse' test_case Hash do method :recurse do test do h = {:a=>1, :b=>{:b1=>1, :b2=>2}} g = h.recurse{|h| h.inject({}){|h,(k,v)| h[k.to_s] = v; h} } g.assert == {"a"=>1, "b"=>{"b1"=>1, "b2"=>2}} end test "with Arrays" do require 'facets/array/recurse' objects = [] struct = {:a => 3, :b => [4, 5, {:c=>6}]} struct.recurse(Array, Hash){|o| objects << o; o } objects.assert.include?( {:c=>6} ) objects.assert.include?( [4, 5, {:c=>6}] ) objects.assert.include?( struct ) objects.length.assert == 3 end end method :recurse! do test do h = {:a=>1, :b=>{:b1=>1, :b2=>2}} h.recurse!{|h| h.inject({}){|h,(k,v)| h[k.to_s] = v; h} } h.assert == {"a"=>1, "b"=>{"b1"=>1, "b2"=>2}} end end end facets-2.9.3/test/core/hash/test_op_push.rb0000644000004100000410000000112411714455226020722 0ustar www-datawww-datacovers 'facets/hash/op_push' test_case Hash do method :<< do test "two element array" do h = {} a = [:b, 2] x = {:b => 2} (h << a).assert == h h.assert == x end test "update new entries" do a = {:a => 1} b = {:b => 2, :c => 3 } x = {:a => 1, :b => 2, :c => 3} (a << b).assert == x a.assert == x end test "update overwrite" do a = {:a => 1, :b => 2, :c => 3} b = {:a => 0, :d => 4} x = {:a => 0, :b => 2, :c => 3, :d => 4} (a << b).assert == x a.assert == x end end end facets-2.9.3/test/core/hash/test_to_struct.rb0000644000004100000410000000053611714455226021301 0ustar www-datawww-datacovers 'facets/hash/to_struct' test_case Hash do method :to_struct do test do h = {:name=>"Dan","age"=>33,"rank"=>"SrA","grade"=>"E4"} s = h.to_struct("Foo") s.name.assert = "Dan" s.age.assert = 33 s.rank.assert = "SrA" s.grade.assert = "E4" #Foo.assert.is_a?(Struct) ? end end end facets-2.9.3/test/core/hash/test_url_params.rb0000644000004100000410000000104511714455226021414 0ustar www-datawww-datacovers 'facets/hash/url_params' testcase Hash do method :url_params do test 'simple hash' do hash1 = {:foo => "bar"} hash1.url_params.assert == "foo=bar" end test 'hash with array value' do hash2 = {"foo" => ["bar", "fab", 1]} hash2.url_params.assert == "foo=bar,fab,1" end test 'hash with multiple elements' do hash3 = {:foo => [:bar, :asdf,1], :fee => 1} params = hash3.url_params params.assert.include? "foo=bar,asdf,1" params.assert.include? "fee=1" end end end facets-2.9.3/test/core/hash/test_update_keys.rb0000644000004100000410000000053511714455226021567 0ustar www-datawww-datacovers 'facets/hash/update_keys' test_case Hash do method :update_keys do test do h = { 'A' => 1, 'B' => 2 } h.update_keys{ |k| k.downcase } h.assert == {'a' => 1, 'b' => 2} end test do h = { :a => 1, :b => 2 } h.update_keys{ |k| "#{k}!" } h.assert == {'a!' => 1, 'b!' => 2} end end end facets-2.9.3/test/core/hash/test_graph.rb0000644000004100000410000000136111714455226020351 0ustar www-datawww-datacovers 'facets/hash/graph' test_case Hash do method :graph! do test "using a hash" do a = { :a => 1, :b => 2, :c => 3 } e = { :a => 2, :b => 3, :c => 4 } a.graph!{ |k,v| { k => v+1 } } a.assert == e end test "using an associative array" do h = {:a=>1,:b=>2,:c=>3} h.graph!{ |k,v| [v, v*v] } h.assert == {1=>1, 2=>4, 3=>9} end end method :mash! do test "using a hash" do a = { :a => 1, :b => 2, :c => 3 } e = { :a => 2, :b => 3, :c => 4 } a.mash!{ |k,v| { k => v+1 } } a.assert == e end test "using an associative array" do h = {:a=>1,:b=>2,:c=>3} h.mash!{ |k,v| [v, v*v] } h.assert == {1=>1, 2=>4, 3=>9} end end end facets-2.9.3/test/core/hash/test_diff.rb0000644000004100000410000000033311714455226020156 0ustar www-datawww-datacovers "facets/hash/diff" test_case Hash do method :diff do test do h1 = {:a=>1,:b=>2} h2 = {:a=>1,:b=>3} h1.diff(h2).assert == {:b=>2} h2.diff(h1).assert == {:b=>3} end end end facets-2.9.3/test/core/hash/test_replace_each.rb0000644000004100000410000000040111714455226021635 0ustar www-datawww-datacovers 'facets/hash/replace_each' test_case Hash do method :replace_each do test do a = { :a => 1, :b => 2, :c => 3 } x = { :a => 2, :b => 3, :c => 4 } a.replace_each{ |k,v| { k => v+1 } } a.assert == x end end end facets-2.9.3/test/core/hash/test_swap.rb0000644000004100000410000000025711714455226020225 0ustar www-datawww-datacovers 'facets/hash/swap' test_case Hash do method :swap! do test do h = { :a=>1, :b=>2 } h.swap!(:a, :b).assert == { :a=>2, :b=>1 } end end end facets-2.9.3/test/core/hash/test_slice.rb0000644000004100000410000000051111714455226020343 0ustar www-datawww-datacovers 'facets/hash/slice' test_case Hash do method :slice do test do h = {:a=>1,:b=>2,:c=>3} h.slice(:a, :b).assert == {:b=>2, :a=>1} end end method :slice! do test do h = {:a=>1,:b=>2,:c=>3} h.slice!(:a, :b).assert == {:c=>3} h.assert == {:a=>1,:b=>2} end end end facets-2.9.3/test/core/hash/test_insert.rb0000644000004100000410000000041111714455226020547 0ustar www-datawww-datacovers 'facets/hash/insert' test_case Hash do method :insert do test do h = {:a=>1, :b=>2} h.assert.insert(:c,3) h.assert == {:a=>1, :b=>2, :c=>3} h.refute.insert(:a,0) h.assert == {:a=>1, :b=>2, :c=>3} end end end facets-2.9.3/test/core/hash/test_alias.rb0000644000004100000410000000063711714455226020346 0ustar www-datawww-datacovers 'facets/hash/alias' test_case Hash do method :alias! do test do foo = { 'a'=>1, 'b'=>2 } foo.alias!('c','b').assert == { 'a'=>1, 'b'=>2, 'c'=>2 } end test do foo = { 'a'=>1, 'b'=>2 } foo.alias!(:a,'a').assert == { :a=>1, 'a'=>1, 'b'=>2 } end test do foo = { :a=>1, :b=>2 } foo.alias!('bar','foo').assert == { :a=>1, :b=>2 } end end end facets-2.9.3/test/core/hash/test_expect.rb0000644000004100000410000000051011714455226020533 0ustar www-datawww-datacovers 'facets/hash/except' test_case Hash do method :except do test do h = {:a=>1, :b=>2, :c=>3} h.except(:a).assert == {:b=>2,:c=>3} end end method :except! do test do h = {:a=>1, :b=>2, :c=>3} h.except!(:a).assert == {:a=>1} h.assert == {:b=>2,:c=>3} end end end facets-2.9.3/test/core/hash/test_op_mul.rb0000644000004100000410000000032011714455226020535 0ustar www-datawww-datacovers 'facets/hash/op_mul' test_case Hash do method :* do test do a = { :a => 1, :b => 2 } b = { :b => 3 } x = { :a => 1, :b => 2 } (a * b).assert == x end end end facets-2.9.3/test/core/hash/test_collate.rb0000644000004100000410000000261111714455226020672 0ustar www-datawww-datacovers 'facets/hash/collate' test_case Hash do setup do @a = { :a=>1, :b=>2, :z=>26, :all=>%w|a b z|, :stuff1=>%w|foo bar|, :whee=>%w|a b| } @b = { :a=>1, :b=>4, :c=>9, :all=>%w|a b c|, :stuff2=>%w|jim jam|, :whee=>%w|a b| } @c = { :a=>1, :b=>8, :c=>27 } end method :collate do test do collated = @a.collate(@b) collated.keys.length.assert == 8 collated[:a].assert == [1,1] collated[:b].assert == [2,4] collated[:c].assert == [9] collated[:z].assert == [26] collated[:all].assert == %w|a b z a b c| collated[:stuff1].assert == %w|foo bar| collated[:stuff2].assert == %w|jim jam| collated[:whee].assert == %w|a b a b| end test "multiple times" do collated = @a.collate(@b).collate(@c) collated[:a].assert == [1,1,1] collated[:b].assert == [2,4,8] collated[:c].assert == [9,27] end end method :collate! do test "in place variant of #collate" do collated = @a.dup collated.collate!(@b) collated.keys.length.assert == 8 collated[:a].assert == [1,1] collated[:b].assert == [2,4] collated[:c].assert == [9] collated[:z].assert == [26] collated[:all].assert == %w|a b z a b c| collated[:stuff1].assert == %w|foo bar| collated[:stuff2].assert == %w|jim jam| collated[:whee].assert == %w|a b a b| end end end facets-2.9.3/test/core/hash/test_argumentize.rb0000644000004100000410000000070711714455226021605 0ustar www-datawww-datacovers 'facets/hash/argumentize' test_case Hash do method :argumentize do setup do @h = { :list => [1,2], :base => "HI" } end test "without an argument field" do @h.argumentize.assert == [ { :list => [1,2], :base => "HI" } ] end test "with an argument field" do @h.argumentize(:list).assert == [ 1, 2, { :base => "HI" } ] @h.argumentize(:base).assert == [ "HI", { :list => [1,2] } ] end end end facets-2.9.3/test/core/hash/test_select.rb0000644000004100000410000000165411714455226020534 0ustar www-datawww-datacovers 'facets/hash/select' test_case Hash do method :select! do test "empty hash" do a = {} a.select!{false}.assert == nil a.assert == {} a = {} a.select!{true}.assert == nil a.assert == {} end test "select none" do a = {0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd'} a.select!{false}.assert == {} a.assert == {} end test "select one" do a = {0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd'} a.select! {|x,y| y == 'b'}.assert == {1 => 'b'} a.assert == {1 => 'b'} end test "select some" do a = {0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd'} a.select! {|x,y| x % 2 == 0}.assert == {0 => 'a', 2 => 'c'} a.assert == {0 => 'a', 2 => 'c'} end test "select all" do a = {0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd'} a.select!{true}.assert == nil a.assert == {0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd'} end end end facets-2.9.3/test/core/hash/test_op_and.rb0000644000004100000410000000076711714455226020521 0ustar www-datawww-datacovers 'facets/hash/op_and' test_case Hash do method :& do test "hash and hash" do a = { :a => 1, :b => 2 } b = { :a => 1 } x = { :a => 1 } (a & b).assert == x end test "hashes with sub-array" do a = { :a => [1], :b => [2] } b = { :a => [1] } x = { :a => [1] } (a & b).assert == x end test "hash and array" do a = { :a => 1, :b => 2 } b = [ :a ] x = { :a => 1 } (a & b).assert == x end end end facets-2.9.3/test/core/hash/test_deep_merge.rb0000644000004100000410000000072711714455226021351 0ustar www-datawww-datacovers 'facets/hash/deep_merge' test_case Hash do method :deep_merge do test do h1 = { :a=>1, :c=>{:x=>10} } h2 = { :b=>2, :c=>{:y=>11} } h = h1.deep_merge(h2) h.assert == {:a=>1, :b=>2, :c=>{:x=>10, :y=>11}} end end method :deep_merge! do test do h1 = { :a=>1, :c=>{:x=>10} } h2 = { :b=>2, :c=>{:y=>11} } h1.deep_merge!(h2) h1.assert == {:a=>1, :b=>2, :c=>{:x=>10, :y=>11}} end end end facets-2.9.3/test/core/hash/test_data.rb0000644000004100000410000000077711714455226020173 0ustar www-datawww-datacovers 'facets/hash/data' test_case Hash do method :data do test do h = {:a=>1, :b=>2} h.data.a.assert == 1 h.data.b.assert == 2 h.data.c.assert == nil end test do h = {:a=>1, :b=>2} h.data.c = 3 h.data.c.assert == 3 end test do h = {:a=>1, :b=>2} # Note, we can't apply a functor to a functor. #h.data.assert.a? #h.data.refute.d? h.data.a?.assert == true h.data.d?.assert == false end end end facets-2.9.3/test/core/hash/test_inverse.rb0000644000004100000410000000037411714455226020726 0ustar www-datawww-datacovers 'facets/hash/inverse' test_case Hash do method :inverse do test do h1 = { :a=>1, :b=>2, :c=>2 } h2 = h1.inverse h2[1].assert == :a h2[2].assert.include?(:b) h2[2].assert.include?(:c) end end end facets-2.9.3/test/core/hash/test_rekey.rb0000644000004100000410000000325111714455226020367 0ustar www-datawww-datacovers 'facets/hash/rekey' test_case Hash do method :rekey do test "default" do foo = { "a"=>1, "b"=>2 } foo.rekey.assert == { :a=>1, :b=>2 } foo.assert == { "a"=>1, "b"=>2 } end test "specific key" do bar = { :a=>1, :b=>2 } foo = bar.rekey(:a=>:c) foo[:c].assert == 1 foo[:b].assert == 2 foo[:a].assert == nil end test "with block" do bar = { :a=>1, :b=>2 } foo = bar.rekey{ |k| k.to_s } foo['a'].assert == 1 foo['b'].assert == 2 foo[:a].assert == nil foo[:b].assert == nil foo.assert == { 'a'=>1, 'b'=>2 } end test "symbol proc" do foo = { :a=>1, :b=>2 } foo.rekey(&:to_s).assert == { "a"=>1, "b"=>2 } foo.assert == { :a =>1, :b=>2 } end end method :rekey! do test "default" do foo = { "a"=>1, "b"=>2 } foo.rekey!.assert == { :a=>1, :b=>2 } foo.assert == { :a=>1, :b=>2 } end test "specific key" do foo = { :a=>1, :b=>2 } foo.rekey!(:a=>:c) foo[:c].assert == 1 foo[:b].assert == 2 foo[:a].assert == nil end test "with block" do foo = { :a=>1, :b=>2 } foo.rekey!{ |k| k.to_s } foo['a'].assert == 1 foo['b'].assert == 2 foo[:a].assert == nil foo[:b].assert == nil foo.assert == { 'a'=>1, 'b'=>2 } end test "symbol proc" do foo = { :a=>1, :b=>2 } foo.rekey!(&:to_s).assert == { "a"=>1, "b"=>2 } foo.assert == { "a"=>1, "b"=>2 } end test "no conflict between keys" do r = {1 => :a, 2 => :b}.rekey!{ |k| k + 1 } r.refute = {3 => :a} r.assert = {2 => :a, 3 => :b} end end end facets-2.9.3/test/core/hash/test_reverse_merge.rb0000644000004100000410000000106111714455226022077 0ustar www-datawww-datacovers 'facets/hash/reverse_merge' test_case Hash do method :reverse_merge do test do h1 = { :a=>1, :b=>2, :c=>2 } h2 = { :c=>3 } h3 = h1.reverse_merge(h2) h3[:c].assert == 2 end end method :reverse_merge! do test do h1 = { :a=>1, :b=>2, :c=>2 } h2 = { :c=>3 } h1.reverse_merge!(h2) h1[:c].assert == 2 end end method :reverse_update do test do h1 = { :a=>1, :b=>2, :c=>2 } h2 = { :c=>3 } h1.reverse_update(h2) h1[:c].assert == 2 end end end facets-2.9.3/test/core/hash/test_to_mod.rb0000644000004100000410000000052211714455226020527 0ustar www-datawww-datacovers 'facets/hash/to_mod' test_case Hash do method :to_mod do test do h = { :a=>1, :b=>2 } m = h.to_mod Module.assert === m end test "check methods" do h = { :a=>1, :b=>2 } m = h.to_mod x = Class.new{ include m }.new x.a.assert == 1 x.b.assert == 2 end end end facets-2.9.3/test/core/hash/test_count.rb0000644000004100000410000000021611714455226020376 0ustar www-datawww-datacovers 'facets/hash/count' test_case Hash do method :count do test do {:A=>1, :B=>1}.count(1).assert == 2 end end end facets-2.9.3/test/core/hash/test_zip.rb0000644000004100000410000000027111714455226020051 0ustar www-datawww-datacovers 'facets/hash/zip' test_case Hash do class_method :zip do test do a = [1,2,3] b = [4,5,6] Hash.zip(a,b).assert == {1=>4,2=>5,3=>6} end end end facets-2.9.3/test/core/hash/test_delete_at.rb0000644000004100000410000000036511714455226021201 0ustar www-datawww-datacovers 'facets/hash/delete_at' test_case Hash do method :delete_at do test do a = { :a => 1, :b => 2, :c => 3 } x = { :b => 2, :c => 3 } v = a.delete_at(:a) v.assert == 1 a.assert == x end end end facets-2.9.3/test/core/hash/test_op_sub.rb0000644000004100000410000000064411714455226020542 0ustar www-datawww-datacovers 'facets/hash/op_sub' test_case Hash do method :- do test "hash minus array" do a = { :a => 1, :b => 2, :c => 3 } b = [ :a ] x = { :b => 2, :c => 3 } (a - b).assert == x end end method :- do test "hash minus hash" do a = { :a => 1, :b => 2, :c => 3 } b = { :a => 1, :d => 4 } x = { :b => 2, :c => 3 } (a - b).assert == x end end end facets-2.9.3/test/core/hash/test_weave.rb0000644000004100000410000000046611714455226020364 0ustar www-datawww-datacovers 'facets/hash/weave' test_case Hash do method :weave do test do b = { :a=>1, :b=>[1,2,3], :c=>{ :x=>'X' } } c = { :a=>2, :b=>[4,5,6], :c=>{ :x=>'A', :y => 'B' } } x = { :a=>2, :b=>[1,2,3,4,5,6], :c=>{ :x => 'A', :y => 'B' } } b.weave(c).assert == x end end end facets-2.9.3/test/core/hash/test_recursively.rb0000644000004100000410000000333311714455226021625 0ustar www-datawww-datacovers 'facets/hash/recursively' covers 'facets/hash/graph' test_case Hash do method :recursively do test "each" do h = {:a=>1,:b=>{:c=>3}} r = [] h.recursively.each{ |k,v| r << [k,v] } r.assert.include? [:a,1] r.assert.include? [:b,{:c=>3}] r.assert.include? [:c,3] end test "map" do h = {:a=>1,:b=>{:c=>3}} r = h.recursively{ |k,v| [k,v] }.map{ |k,v| [k, v.succ] } r.assert.include? [:a,2] r.assert.include? [:b,[[:c,4]]] end test "map (moot)" do h = {:a=>1,:b=>{:c=>3}} a = h.recursively.map{ |k,v| [k, v] } a.assert.include? [:a,1] a.assert.include? [:b,[[:c,3]]] end test 'graph' do h = {:a=>1,:b=>{:c=>3}} r = h.recursively{ |k,v| [k.to_s, v] }.graph{ |k,v| [k.to_s, v.to_s] } r.assert == {'a'=>'1','b'=>{'c'=>'3'}} end test 'graph!' do h = {:a=>1,:b=>{:c=>3}} h.recursively{ |k,v| [k.to_s, v] }.graph!{ |k,v| [k.to_s, v.to_s] } h.assert == {'a'=>'1','b'=>{'c'=>'3'}} end test 'mash' do h = {:a=>1,:b=>{:c=>3}} r = h.recursively{ |k,v| [k.to_s, v] }.mash{ |k,v| [k.to_s, v.to_s] } r.assert == {'a'=>'1','b'=>{'c'=>'3'}} end test 'mash!' do h = {:a=>1,:b=>{:c=>3}} h.recursively{ |k,v| [k.to_s, v] }.mash!{ |k,v| [k.to_s, v.to_s] } h.assert == {'a'=>'1','b'=>{'c'=>'3'}} end #test 'merge' do # h1 = {:a=>1,:b=>{:c=>3}} # h2 = {:b=>{:d=>4}} # r = h1.recursively.merge(h2) # r.assert == {:a=>1,:b=>{:c=>3, :d=>4}} #end #test 'merge!' do # h1 = {:a=>1,:b=>{:c=>3}} # h2 = {:b=>{:d=>4}} # h1.recursively.merge!(h2) # h1.assert == {:a=>1,:b=>{:c=>3, :d=>4}} #end end end facets-2.9.3/test/core/hash/test_at.rb0000644000004100000410000000025711714455226017657 0ustar www-datawww-datacovers 'facets/hash/at' test_case Hash do method :at do test do h = { :a=>1, :b=>2 } h.at(:a).assert == 1 h.at(:b).assert == 2 end end end facets-2.9.3/test/core/hash/test_op_or.rb0000644000004100000410000000031611714455226020365 0ustar www-datawww-datacovers 'facets/hash/op_or' test_case Hash do method :| do test do a = { :a => 1, :b => 2 } b = { :b => 3 } x = { :a => 1, :b => 2 } (a | b).assert == x end end end facets-2.9.3/test/core/hash/test_dearray_values.rb0000644000004100000410000000070111714455226022253 0ustar www-datawww-datacovers 'facets/hash/dearray_values' test_case Hash do method :dearray_values do test do h = { :a=>[1], :b=>[1,2], :c=>3, :d=>[] } x = { :a=>1, :b=>1, :c=>3, :d=>nil } h.dearray_values.assert == x end end method :dearray_singular_values do test do h = { :a=>[1], :b=>[1,2], :c=>3, :d=>[] } x = { :a=>1, :b=>[1,2], :c=>3, :d=>nil } h.dearray_singular_values.assert == x end end end facets-2.9.3/test/core/dir/0000755000004100000410000000000011714455226015516 5ustar www-datawww-datafacets-2.9.3/test/core/dir/test_each_child.rb0000644000004100000410000000045111714455226021145 0ustar www-datawww-datacovers 'facets/dir/each_child' test_case Dir do test_directory = 'test' method :each_child do test do c = [] d = Dir.new(test_directory) d.each_child do |path| c << path end d.close c.sort.assert == ['core', 'standard'] end end end facets-2.9.3/test/core/dir/test_recurse.rb0000644000004100000410000000063611714455226020557 0ustar www-datawww-datacovers 'facets/dir/recurse' test_case Dir do class_method :recurse do test do r = Dir.recurse('test') r.assert.include?('test/core/dir') r.assert.include?('test/core/dir/test_recurse.rb') end end class_method :ls_r do test do r = Dir.ls_r('test') r.assert.include?('test/core/dir') r.assert.include?('test/core/dir/test_recurse.rb') end end end facets-2.9.3/test/core/dir/test_descend.rb0000644000004100000410000000055711714455226020516 0ustar www-datawww-datacovers 'facets/dir/ascend' test_case Dir do test_directory = 'test/core/dir' class_method :descend do test do c = [] Dir.descend(test_directory) do |path| c << path end rdir = test_directory c.reverse_each do |d| d.assert == rdir rdir = File.dirname(rdir) end end end end facets-2.9.3/test/core/dir/test_multiglob.rb0000644000004100000410000000057711714455226021111 0ustar www-datawww-datacovers 'facets/dir/multiglob' test_case Dir do class_method :multiglob do test do r = Dir.multiglob('test/c*').sort r.assert == ['test/core'] end end class_method :multiglob_r do test do r = Dir.multiglob_r('test').sort r.assert.include?('test/core/dir') r.assert.include?('test/core/dir/test_multiglob.rb') end end end facets-2.9.3/test/core/dir/test_ascend.rb0000644000004100000410000000123111714455226020334 0ustar www-datawww-datacovers 'facets/dir/ascend' test_case Dir do test_directory = 'test/core/dir' class_method :ascend do test do c = [] Dir.ascend(test_directory) do |path| c << path end rdir = test_directory c.each do |d| d.assert == rdir rdir = File.dirname(rdir) end end end class_method :ascend do test "exclude current" do c = [] Dir.ascend(test_directory, false) do |path| c << path end rdir = File.dirname(test_directory) c.each do |d| d.assert == rdir rdir = File.dirname(rdir) end end end end facets-2.9.3/test/core/dir/test_parent.rb0000644000004100000410000000023011714455226020366 0ustar www-datawww-datacovers 'facets/dir/parent' test_case Dir do class_method :parent? do test do Dir.assert.parent?("a/b/c", "a/b/c/d") end end end facets-2.9.3/test/core/kernel/0000755000004100000410000000000011714455226016220 5ustar www-datawww-datafacets-2.9.3/test/core/kernel/test_ask.rb0000644000004100000410000000014511714455226020362 0ustar www-datawww-datacovers 'facets/kernel/ask' test_case Kernel do # requires user input method :ask do end end facets-2.9.3/test/core/kernel/test_object_class.rb0000644000004100000410000000044111714455226022236 0ustar www-datawww-datacovers 'facets/kernel/object_class' covers 'facets/kernel/__class__' test_case Kernel do method :object_class do test do self.object_class.assert == self.class end end method :__class__ do test do self.__class__.assert == self.class end end end facets-2.9.3/test/core/kernel/test_try.rb0000644000004100000410000000075311714455226020427 0ustar www-datawww-datacovers 'facets/kernel/try' test_case Kernel do method :try do test do example = Struct.new(:name).new("bob") example.try(:name).assert == "bob" end test "without argument" do example = Struct.new(:name).new("bob") example.try.name.assert == "bob" end end end test_case NilClass do method :try do test do nil.try(:name).assert == nil end test "without argument" do nil.try.name.assert == nil end end end facets-2.9.3/test/core/kernel/test_extension.rb0000644000004100000410000000034411714455226021621 0ustar www-datawww-datacovers 'facets/kernel/extension' test_case Kernel do # DEPRECATE ? method :extension do test do c = Class.new o = c.new x = (class << o; self; end) o.extension.assert == x end end end facets-2.9.3/test/core/kernel/test_with.rb0000644000004100000410000000033411714455226020557 0ustar www-datawww-datacovers 'facets/kernel/with' test_case Kernel do method :with do test do with values = [] do self << 'bar' self << 'baz' end values.assert == ['bar', 'baz'] end end end facets-2.9.3/test/core/kernel/test_meta_eval.rb0000644000004100000410000000045611714455226021546 0ustar www-datawww-datacovers 'facets/kernel/meta_eval' test_case Kernel do method :meta_eval do test do o = Object.new o.meta_eval do @y = "y" end o.instance_variable_get("@y").refute == "y" (class << o; self; end).instance_variable_get("@y").assert == "y" end end end facets-2.9.3/test/core/kernel/test_not_nil.rb0000644000004100000410000000042211714455226021244 0ustar www-datawww-datacovers 'facets/kernel/not_nil' test_case Kernel do method :not_nil? do test do 5.assert.not_nil? end test do :x.assert.not_nil? end test do false.assert.not_nil? end test do nil.refute.not_nil? end end end facets-2.9.3/test/core/kernel/test_deep_copy.rb0000644000004100000410000000116311714455226021554 0ustar www-datawww-datacovers 'facets/kernel/deep_copy' test_case Kernel do method :deep_copy do test do o = "This is a week test." d = o.deep_copy d.assert == "This is a week test." end end method :deep_clone do setup "a class with reference to another class" do xC = Class.new do attr_reader :x def initialize @x = 1 end end @c = Class.new do attr_reader :y define_method(:initialize) do @y = xC.new end end end test do o = @c.new d = o.deep_clone d.y.x.assert == 1 end end end facets-2.9.3/test/core/kernel/test_object_send.rb0000644000004100000410000000056311714455226022067 0ustar www-datawww-datacovers 'facets/kernel/object_send' test_case Kernel do method :object_send do test "same as #public_send of Ruby 1.9+" do c = Class.new do def x; "x"; end private def y; "y"; end end o = c.new o.object_send(:x).assert == "x" expect NoMethodError do o.object_send(:y) end end end end facets-2.9.3/test/core/kernel/test_assign_from.rb0000644000004100000410000000137611714455226022122 0ustar www-datawww-datacovers 'facets/kernel/assign_from' test_case Kernel do c = Struct.new(:name, :address, :zip) method :assign_from do test do bob = c.new("Bob Sawyer", "123 Maple, Anytown NC", 12345) joe = c.new("Joe Pitare") joe.assign_from(bob, :address, :zip) joe.name.assert == "Joe Pitare" joe.address. == "123 Maple, Anytown NC" joe.zip.assert == 12345 end end method :assign_from do c1 = Class.new do attr_accessor :a attr_accessor :b end c2 = Class.new do attr_accessor :a attr_accessor :b end test do o1 = c1.new o1.a = 1 o1.b = 2 o2 = c2.new o2.assign_from(o1, :a, :b) o2.a.assert == 1 o2.b.assert == 2 end end end facets-2.9.3/test/core/kernel/test_not.rb0000644000004100000410000000116311714455226020405 0ustar www-datawww-datacovers 'facets/kernel/not' test_case Kernel do method :not? do test do b = true b.not?.assert == !b end test :not? do b = false b.not?.assert == !b end test :not? do b = nil b.not?.assert == !b end test :not? do b = Object.new b.not?.assert == !b end end method :not do test do b = true r = b.not.nil? r.assert == true end test :not do b = false r = b.not.nil? r.assert == true end test :not do b = nil r = b.not.nil? r.assert == false end end end facets-2.9.3/test/core/kernel/test_ergo.rb0000644000004100000410000000067711714455226020552 0ustar www-datawww-datacovers 'facets/kernel/ergo' test_case Kernel do method :ergo do test do "a".ergo.upcase.assert == "A" nil.ergo.foobar.assert == nil end test do "a".ergo{ |o| o.upcase }.assert == "A" nil.ergo{ |o| o.foobar }.assert == nil end end end test_case NilClass do method :ergo do test do "a".ergo{ |o| o.upcase }.assert == "A" nil.ergo{ |o| o.bar }.assert == nil end end end facets-2.9.3/test/core/kernel/test_attr_singleton.rb0000644000004100000410000000141711714455226022643 0ustar www-datawww-datacovers 'facets/kernel/attr_singleton' test_case Kernel do c = Class.new do def initialize attr_singleton_reader :foo #=> "FOO" attr_singleton_writer :bar #=> "BAR" attr_singleton_accessor :baz #=> "BAZ" @foo = "FOO" self.bar = "BAR" self.baz = "BAZ" end def get_bar @bar end end method :attr_singleton_reader do test do t = c.new t.foo.assert == "FOO" end end method :attr_singleton_writer do test do t = c.new t.get_bar.assert == "BAR" t.bar = "BAR2" t.get_bar.assert == "BAR2" end end method :attr_singleton_accessor do test do t = c.new t.baz.assert == "BAZ" t.baz = "BAZ2" t.baz.assert == "BAZ2" end end end facets-2.9.3/test/core/kernel/test_true.rb0000644000004100000410000000071411714455226020565 0ustar www-datawww-datacovers 'facets/kernel/true' test_case Kernel do method :true? do test "nothing is true? but true itself" do true.assert.true? nil.refute.true? false.refute.true? 1.refute.true? :a.refute.true? end end method :false? do test "nothing is false? but false itself" do false.assert.false? nil.refute.false? true.refute.false? 1.refute.false? :a.refute.false? end end end facets-2.9.3/test/core/kernel/test_in.rb0000644000004100000410000000023411714455226020211 0ustar www-datawww-datacovers 'facets/kernel/in' test_case Kernel do method :in? do test do 5.assert.in?(0..10) 5.assert.in?([1,2,3,4,5]) end end end facets-2.9.3/test/core/kernel/test_method.rb0000644000004100000410000000047211714455226021067 0ustar www-datawww-datacovers 'facets/kernel/method' test_case Kernel do method :method! do test do c = Class.new do def foo ; 'foo' ; end end ic = c.new ic.method(:foo).__id__.refute == ic.method(:foo).__id__ ic.method!(:foo).__id__.assert == ic.method!(:foo).__id__ end end end facets-2.9.3/test/core/kernel/test_instance_assign.rb0000644000004100000410000000045011714455226022753 0ustar www-datawww-datacovers 'facets/kernel/instance_assign' test_case Kernel do method :instance_assign do test do ahash = { "z"=>0, "@a"=>1, "@b"=>2 } #, "@@a"=>3 } instance_assign(ahash) @z.assert == 0 @a.assert == 1 @b.assert == 2 #@@a.assert == 3 end end end facets-2.9.3/test/core/kernel/test_maybe.rb0000644000004100000410000000016311714455226020701 0ustar www-datawww-datacovers 'facets/kernel/maybe' test_case Kernel do method :maybe do test do maybe end end end facets-2.9.3/test/core/kernel/test_get.rb0000644000004100000410000000155411714455226020370 0ustar www-datawww-datacovers 'facets/kernel/__get__' covers 'facets/kernel/__set__' test_case Kernel do method :__get__ do setup "an object with an instance variable" do c = Class.new do attr :a def initialize @a = 1 end end @o = c.new end test do @o.__get__('@a').assert == 1 end # TODO: support is being considered #test "wihtout at-sign" do |o| # o.__get__(:a).assert == 1 #end end method :__set__ do setup "an object with an instance variable" do c = Class.new do attr :a def initialize @a = 1 end end @o = c.new end test do @o.__set__('@a', 2) @o.a.assert == 2 end # TODO: support is being considered #test "without at-sign" do # @o.__set__(:a, 3) # @o.a.assert == 3 #end end end facets-2.9.3/test/core/kernel/test_here.rb0000644000004100000410000000020611714455226020525 0ustar www-datawww-datacovers 'facets/kernel/here' test_case Kernel do method :here do test do here.assert.is_a?(Binding) end end end facets-2.9.3/test/core/kernel/test_constant.rb0000644000004100000410000000041111714455226021431 0ustar www-datawww-datacovers 'facets/kernel/constant' test_case Kernel do method :constant do test do c = ::Lemon::TestCase.name constant(c).assert == ::Lemon::TestCase c = "TestCase" ::Lemon.constant(c).assert == ::Lemon::TestCase end end end facets-2.9.3/test/core/kernel/test_source_location.rb0000644000004100000410000000070511714455226022776 0ustar www-datawww-datacovers 'facets/kernel/source_location' test_case Kernel do # TODO: lemon seems to interfer with call stack method :source_location do test do raise Omission, "issue with call stack" file, line, meth = source_location_example file.assert == __FILE__ line.assert == 13 meth.assert == :source_location_example end # helper method def source_location_example source_location end end end facets-2.9.3/test/core/kernel/test_val.rb0000644000004100000410000000060311714455226020365 0ustar www-datawww-datacovers 'facets/kernel/val' test_case Kernel do method :val? do test "of nil" do f = nil t = 1 f.refute.val? t.assert.val? end test "of empty array" do f = [] t = [1] f.refute.val? t.assert.val? end test "of empty string" do f = '' t = '1' f.refute.val? t.assert.val? end end end facets-2.9.3/test/core/kernel/test_silence.rb0000644000004100000410000000052011714455226021223 0ustar www-datawww-datacovers 'facets/kernel/silence' test_case Kernel do # TODO: figure out how to test silence methods concern "Not straight foward to test since they effect output." method :silence do end method :silence_stream do end method :silence_stderr do end method :silence_stdout do end method :silently do end end facets-2.9.3/test/core/kernel/test_presence.rb0000644000004100000410000000116111714455226021407 0ustar www-datawww-datacovers 'facets/kernel/presence' test_case Kernel do method :presence do test do "a".presence.assert == "a" [1].presence.assert == [1] {:a=>1}.presence.assert == {:a=>1} end test do "".presence.assert == nil [].presence.assert == nil {}.presence.assert == nil end end method :present? do test "non-empty objects are present" do "a".assert.present? [1].assert.present? {:a=>1}.assert.present? end test "empty object are not present" do "".refute.present? [].refute.present? {}.refute.present? end end end facets-2.9.3/test/core/kernel/test_d.rb0000644000004100000410000000020711714455226020026 0ustar www-datawww-datacovers 'facets/kernel/d' test_case Kernel do # TODO: how to test #d silently? Need to redirect $stderr. method :d do end end facets-2.9.3/test/core/kernel/test_disable_warnings.rb0000644000004100000410000000106611714455226023122 0ustar www-datawww-datacovers 'facets/kernel/disable_warnings' covers 'facets/kernel/enable_warnings' covers 'facets/kernel/silence_warnings' test_case Kernel do method :disable_warnings do test do disable_warnings do assert( ! $VERBOSE ) end end end method :silence_warnings do test "alias for backward compatibility" do silence_warnings do assert( ! $VERBOSE ) end end end method :enable_warnings do test :enable_warnings do enable_warnings do assert( $VERBOSE ) end end end end facets-2.9.3/test/core/kernel/test_writers.rb0000644000004100000410000000164111714455226021305 0ustar www-datawww-datacovers 'facets/kernel/writers' test_case Kernel do method :writers do test do c = Class.new do attr_accessor :a def b=(b); @b=b; end end o = c.new w = o.writers w.assert.include?(:a=) w.assert.include?(:b=) end test do c = Class.new do attr_accessor :a def b=(b); @b=b; end private def q=(q); @q=q; end end o = c.new w = o.writers(:access=>:private) w.refute.include?(:a=) w.refute.include?(:b=) w.assert.include?(:q=) end test do c = Class.new do attr_accessor :a def b=(b); @b=b; end private def q=(q); @q=q; end end o = c.new w = o.writers(:access=>:all) w.assert.include?(:a=) w.assert.include?(:b=) w.assert.include?(:q=) end # TODO: Need to test more options for writers. end end facets-2.9.3/test/core/kernel/test_dir.rb0000644000004100000410000000076111714455226020366 0ustar www-datawww-datacovers 'facets/kernel/__dir__' test_case Kernel do # TODO: can't test b/c somehow Lemon intefers with the call stack # which __DIR__ uses to locate the current running file. method :__DIR__ do omit "issue with call stack" do test "relative directory" do __DIR__.assert == File.dirname(__FILE__) end test "relative directory joins with arguments" do __DIR__('tmp').assert == File.join(File.dirname(__FILE__), 'tmp') end end end end facets-2.9.3/test/core/kernel/test_temporarily.rb0000644000004100000410000000070211714455226022152 0ustar www-datawww-datacovers 'facets/kernel/temporarily' test_case Kernel do method :temporarily do test "global variable" do $temporary_variable = true temporarily('$temporary_variable'=>false) do $temporary_variable.assert == false end $temporary_variable.assert == true end test "instance variable" do @x = 1 temporarily('@x'=>2) do @x.assert == 2 end @x.assert == 1 end end end facets-2.9.3/test/core/kernel/test_instance_class.rb0000644000004100000410000000031011714455226022567 0ustar www-datawww-datacovers 'facets/kernel/instance_class' test_case Kernel do method :instance_class do test do o = Object.new o.instance_class.assert == (class << o; self; end) end end end facets-2.9.3/test/core/kernel/test_object_hexid.rb0000644000004100000410000000046511714455226022240 0ustar www-datawww-datacovers 'facets/kernel/object_hexid' test_case Kernel do method :object_hexid do omit "too inconsitent across platforms" do test do o = Object.new "#".assert == o.inspect #assert(o.inspect.index(o.object_hexid)) end end end end facets-2.9.3/test/core/kernel/test_meta_def.rb0000644000004100000410000000026411714455226021352 0ustar www-datawww-datacovers 'facets/kernel/meta_def' test_case Kernel do method :meta_def do test do x = Class.new x.meta_def(:x){"x"} x.x.assert == "x" end end end facets-2.9.3/test/core/kernel/test_assign.rb0000644000004100000410000000246311714455226021075 0ustar www-datawww-datacovers 'facets/kernel/assign' test_case Kernel do method :assign do setup do @c = Struct.new(:name, :address, :zip) end test "with arguments" do bob = @c.new bob.assign(:name, "Bob Sawyer") bob.assign(:address, "123 Maple, Anytown NC") bob.assign(:zip, 12345) bob.name.assert == "Bob Sawyer" bob.address.assert == "123 Maple, Anytown NC" bob.zip.assert == 12345 end test "with hash" do bob = @c.new x = { :name => "Bob Sawyer", :address => "123 Maple, Anytown NC", :zip => 12345 } bob.assign(x) bob.name.assert == x[:name] bob.address.assert == x[:address] bob.zip.assert == x[:zip] end test "with associative array" do bob = @c.new x = [[:name, "Bob Sawyer"], [:address, "123 Maple, Anytown NC"], [:zip, 12345]] bob.assign(x) bob.name.assert == "Bob Sawyer" bob.address.assert == "123 Maple, Anytown NC" bob.zip.assert == 12345 end #test "with block" do # bob = @c.new # # x = lambda {|s| s.name = "Bob Sawyer"; s.address = "123 Maple, Anytown NC"; s.zip = 12345 } # # bob.assign(&x) # # bob.name.assert == "Bob Sawyer" # bob.address.assert == "123 Maple, Anytown NC" # bob.zip.assert == 12345 #end end end facets-2.9.3/test/core/kernel/test_callstack.rb0000644000004100000410000000030511714455226021543 0ustar www-datawww-datacovers 'facets/kernel/callstack' test_case Kernel do method :call_stack do test do call_stack end end method :callstack do test do callstack end end end facets-2.9.3/test/core/kernel/test_qua_class.rb0000644000004100000410000000051311714455226021556 0ustar www-datawww-datacovers 'facets/kernel/qua_class' test_case Kernel do method :qua_class do test do o = Object.new s = (class << o; self; end) o.qua_class.assert == s end end method :quaclass do test do o = Object.new s = (class << o; self; end) o.quaclass.assert == s end end end facets-2.9.3/test/core/kernel/test_super_method.rb0000644000004100000410000000063111714455226022302 0ustar www-datawww-datacovers 'facets/kernel/super_method' test_case Kernel do method :super_method do setup "class heirarchy" do @x = Class.new{ def x ; 1 ; end } @y = Class.new(@x){ def x ; 2 ; end } @z = Class.new(@y){ def x ; 3 ; end } end test do x = @x.new z = @z.new s0 = x.method(:x) s1 = z.super_method(@x, :x) s1.call.assert == s0.call end end end facets-2.9.3/test/core/kernel/test_meta_alias.rb0000644000004100000410000000036111714455226021703 0ustar www-datawww-datacovers 'facets/kernel/meta_alias' test_case Kernel do method :meta_alias do test do c = Class.new do def self.y?; "y?" ; end end c.meta_alias "ynot?", "y?" c.ynot?.assert == "y?" end end end facets-2.9.3/test/core/kernel/test_complete.rb0000644000004100000410000000034711714455226021420 0ustar www-datawww-datacovers 'facets/kernel/complete' test_case Kernel do method :complete do test do a = [] i = 0 complete do i += 1 i == 3 ? nil : a << i end a.assert == [1,2] end end end facets-2.9.3/test/core/kernel/test_singleton_class.rb0000644000004100000410000000032511714455226022773 0ustar www-datawww-datacovers 'facets/kernel/singleton_class' test_case Kernel do method :singleton_class do test do x = Class.new m = (class << x; self; end) x.singleton_class.assert == m end end end facets-2.9.3/test/core/kernel/test_require_all.rb0000644000004100000410000000017211714455226022110 0ustar www-datawww-datacovers 'facets/kernel/require_all' test_case Kernel do method :require_all do end method :load_all do end end facets-2.9.3/test/core/kernel/test_blank.rb0000644000004100000410000000247111714455226020677 0ustar www-datawww-datacovers 'facets/kernel/blank' # NOTE: Using x.assert.blank? here caused AE some issues # b/c of problems with Assertor. Basically Assertor needs # to subclass BasicObject, but Ruby 1.9 has constant lookup # issues with BasicObject that need address. So in this case # we'll just use the old-school `assert foo` syntax. test_case Kernel do method :blank? do test do refute Object.new.blank? end end end test_case NilClass do method :blank? do test do assert nil.blank? end end end test_case FalseClass do method :blank? do test do assert false.blank? end end end test_case TrueClass do method :blank? do test do refute true.blank? end end end test_case Array do method :blank? do test do assert [].blank? refute [1].blank? end end end test_case Hash do method :blank? do test do assert( {}.blank? ) refute( {:a=>1}.blank? ) end end end test_case String do method :blank? do test do refute "xyz".blank? assert " ".blank? end end end test_case Numeric do method :blank? do test do refute 0.blank? end end method :blank? do test do refute 10.blank? end end method :blank? do test do refute 10.0.blank? end end end facets-2.9.3/test/core/kernel/test_instance_send.rb0000644000004100000410000000060111714455226022416 0ustar www-datawww-datacovers 'facets/kernel/instance_send' test_case Kernel do method :instance_send do test "alias for #send" do c = Class.new do def x; "x"; end private def y; "y"; end end o = c.new expect NoMethodError do o.y end o.instance_send(:x).assert == "x" o.instance_send(:y).assert == "y" end end end facets-2.9.3/test/core/kernel/test_meta_class.rb0000644000004100000410000000076011714455226021722 0ustar www-datawww-datacovers 'facets/kernel/meta_class' test_case Kernel do method :meta_class do test do x = Class.new m = (class << x; self; end) x.meta_class.assert == m end test "class_eval block on meta class" do c = Class.new c.meta_class do def foo; "foo"; end end c.foo.assert == "foo" end end method :metaclass do test do x = Class.new m = (class << x; self; end) x.metaclass.assert == m end end end facets-2.9.3/test/core/kernel/test_require_relative.rb0000644000004100000410000000025611714455226023156 0ustar www-datawww-datacovers 'facets/kernel/require_relative' covers 'facets/kernel/load_relative' test_case Kernel do method :require_relative do end method :load_relative do end end facets-2.9.3/test/core/kernel/test_tap.rb0000644000004100000410000000123611714455226020372 0ustar www-datawww-datacovers 'facets/kernel/tap' test_case Kernel do method :tap do test do e = "foo" r = "foobar".tap{ |x| x.gsub!(/bar/, '') } r.assert == e end test "check internal value" do x = [1,2,3] x.tap{ |a| a.assert == x } end test "assign via tap block" do bob = Struct.new(:name, :address, :zip).new x = lambda do |s| s.name = "Bob Sawyer" s.address = "123 Maple, Anytown NC" s.zip = "12345" end bob.tap(&x) bob.name.assert == "Bob Sawyer" bob.address.assert == "123 Maple, Anytown NC" bob.zip.assert == "12345" end end end facets-2.9.3/test/core/kernel/test_hierarchical_send.rb0000644000004100000410000000130111714455226023226 0ustar www-datawww-datarequire 'facets/kernel/hierarchical_send' test_case Object do setup do m = Module.new do attr :a def preinitialize @a = 10 end end @x = Class.new do include m attr :b def preinitialize @b = 20 end def initialize hierarchical_send(:preinitialize) end end @y = Class.new(@x) do def initialize @a = "not 10" @b = "not 20" super end end end method :hierarchical_send do test do x = @x.new x.a.assert == 10 x.b.assert == 20 end test 'subclass' do y = @y.new y.a.assert == 10 y.b.assert == 20 end end end facets-2.9.3/test/core/kernel/test_class.rb0000644000004100000410000000025011714455226020706 0ustar www-datawww-datacovers 'facets/kernel/__class__' test_case Kernel do method :__class__ do test do o = Object.new o.__class__.assert == o.class end end end facets-2.9.3/test/core/kernel/test_respond.rb0000644000004100000410000000121211714455226021252 0ustar www-datawww-datacovers 'facets/kernel/respond' test_case Kernel do method :respond do test do c = Class.new do def f; "f"; end end x = c.new x.respond(:f).assert == "f" x.respond(:g).assert == nil x.respond.f.assert == "f" x.respond.g.assert == nil end end # #method :respond_with_value do # test do # c = Class.new do # def f; "f"; end # end # # x = c.new # x.respond_with_value(:f).assert == "f" # x.respond_with_value(:g).assert == nil # # x.respond_with_value.f.assert == "f" # x.respond_with_value.g.assert == nil # end #end end facets-2.9.3/test/core/kernel/test_returning.rb0000644000004100000410000000036411714455226021624 0ustar www-datawww-datacovers 'facets/kernel/returning' test_case Kernel do method :returning do test do foo = returning( values = [] ) do values << 'bar' values << 'baz' end foo.assert == ['bar', 'baz'] end end end facets-2.9.3/test/core/kernel/test_as.rb0000644000004100000410000000223211714455226020206 0ustar www-datawww-datacovers 'facets/kernel/as' test_case Kernel do setup "class heirarchy" do a = Class.new do def x; "a.x"; end def y; "a.y"; end end b = Class.new(a) do def x; "b.x" end def y; "b.y" end end c = Class.new(b) do def x; "c.x"; end define_method(:y){ as(a).x } end @a, @b, @c = a, b, c end method :as do test do o = @c.new o.x.assert == "c.x" o.y.assert == "a.x" end end method :send_as do test do s = "a" def s.class; nil; end s.class.refute == String s.send_as(Object, :class).assert == String end end #setup "class heirarchy" do # x = Class.new{ def x ; 1 ; end } # y = Class.new(x){ def x ; 2 ; end } # z = Class.new(y){ define_method(:x){ super_as(x) } } # z #end #method :super_as do |z| # o = z.new # o.x.assert == 1 #end end test_case As do class_method :new do setup do @c = Class.new(String) do def to_s; "denied"; end end end test do o = @c.new("hi") o.to_s.assert == "denied" As.new(o, String).to_s.assert == "hi" end end end facets-2.9.3/test/core/object/0000755000004100000410000000000011714455226016206 5ustar www-datawww-datafacets-2.9.3/test/core/object/test_replace.rb0000644000004100000410000000205611714455226021210 0ustar www-datawww-datacovers 'facets/object/replace' test_case Object do method :replace do test "must be the same type" do c = Class.new do attr_reader :a, :b def initialize(a,b) @a, @b = a, b end end o = c.new(1,2) o.a.assert == 1 o.b.assert == 2 # TODO: TypeError ? expect ArgumentError do o.replace(:a=>3, :b=>4) end end test do c = Class.new do attr :name attr :age def initialize(name, age) @name, @age = name, age end end a = c.new('bob', 60) a.name.assert == 'bob' a.age.assert == 60 b = c.new('tom', 40) a.replace(b) a.name.assert == 'tom' a.age.assert == 40 end end end test_case Struct do method :replace do test do s = Struct.new(:name, :age) o = s.new('bob', 60) o.name.assert == 'bob' o.age.assert == 60 o.replace(:name=>'tom', :age=>40) o.name.assert == 'tom' o.age.assert == 40 end end end facets-2.9.3/test/core/object/test_dup.rb0000644000004100000410000000322211714455226020361 0ustar www-datawww-datacovers 'facets/object/dup' # TODO: Improve object/dup tests. test_case Object do setup "ordinary object" do @o = Object.new end method :dup? do test { assert @o.dup? } end method :clone? do test { assert @o.clone? } end method :dup! do test { assert @o.dup! } end method :try_dup do |o| test { assert @o.try_dup } end end test_case TrueClass do method :dup? do test { refute true.dup? } end method :clone? do test { refute true.clone? } end method :dup! do test { assert true.dup! } end method :try_dup do test { assert true.try_dup } end end test_case FalseClass do method :dup? do test { refute false.dup? } end method :clone? do test { refute false.clone? } end method :dup! do test { false.dup!.assert == false } end method :try_dup do test { false.try_dup.assert == false } end end test_case NilClass do method :dup? do test { refute nil.dup? } end method :clone? do test { refute nil.clone? } end method :dup! do test { nil.dup!.assert == nil } end method :try_dup do test { nil.try_dup.assert == nil } end end test_case Symbol do method :dup? do test { refute :a.dup? } end method :clone? do test { refute :a.clone? } end method :dup! do test { :a.dup!.assert == :a } end method :try_dup do test { :a.try_dup.assert == :a } end end test_case Numeric do method :dup? do test { refute 1.dup? } end method :clone? do test { refute 1.clone? } end method :dup! do test { 1.dup!.assert == 1 } end method :try_dup do test { 1.try_dup.assert == 1 } end end facets-2.9.3/test/core/object/test_try_dup.rb0000644000004100000410000000156411714455226021266 0ustar www-datawww-datacovers 'facets/object/try_dup' test_case Object do method :try_dup do test do obj1 = Object.new obj2 = obj1.try_dup obj2.equal?(obj1).assert == false end end method :dup! do test "is an alias for #try_dup" do obj1 = Object.new obj2 = obj1.dup! obj2.equal?(obj1).assert == false end end end test_case TrueClass do method :try_dup do test do true.try_dup.assert == true end end end test_case FalseClass do method :try_dup do test do false.try_dup.assert == false end end end test_case NilClass do method :try_dup do test do nil.try_dup.assert == nil end end end test_case Numeric do method :try_dup do test do 10.try_dup.assert == 10 end end end test_case Symbol do method :try_dup do test do :A.try_dup.assert == :A end end end facets-2.9.3/test/core/object/test_object_state.rb0000644000004100000410000000223711714455226022244 0ustar www-datawww-datacovers 'facets/object/object_state' test_case Object do method :object_state do test do c = Class.new do def initialize(a,b) @a, @b = a, b end end o = c.new(1,2) s = o.object_state s.assert == {:a=>1, :b=>2} end end end test_case Struct do method :object_state do test do c = Struct.new(:a, :b) o = c.new(1,2) s = o.object_state s.assert == {:a=>1, :b=>2} end end end test_case Array do method :object_state do test do a = [1,2,3,4] s = a.object_state s.assert == a end end end test_case Hash do method :object_state do test do h = {:a=>1,:b=>2,:c=>3} s = h.object_state s.assert == h end end end test_case String do method :object_state do test do t = "test string" s = t.object_state s.assert == t end end end #test_case Kernel do # # method :object_state do # test do # c = Class.new do # def initialize(a,b) # @a, @b = a, b # end # end # o = c.new(1,2) # s = o.object_state # s.assert == {:a=>1, :b=>2} # end # end # #end facets-2.9.3/test/core/time/0000755000004100000410000000000011714455226015676 5ustar www-datawww-datafacets-2.9.3/test/core/time/test_elapse.rb0000644000004100000410000000026511714455226020536 0ustar www-datawww-datacovers 'facets/time/elapse' test_case Time do class_method :elapse do test do t = Time.elapse { sleep 1 } assert( (t > 0.9) && (t < 2.1 )) end end end facets-2.9.3/test/core/time/test_trunc.rb0000644000004100000410000000115211714455226020414 0ustar www-datawww-datacovers 'facets/time/trunc' test_case Time do method :trunc do setup do @t = Time.local(2000,03,03,3,37,23) end test "hour" do @t.trunc(60 * 60).assert == Time.local(2000,03,03,3, 0) end #test "month" do # @t.trunc(1.month).assert == Time.local(2000,03,01,0, 0) #end test "15 minutes" do @t.trunc(15 * 60).assert == Time.local(2000,03,03,3,30) end test "10 minutes" do @t.trunc(10 * 60).assert == Time.local(2000,03,03,3,30) end test "05 minutes" do @t.trunc(5 * 60).assert == Time.local(2000,03,03,3,35) end end end facets-2.9.3/test/core/time/test_hence.rb0000644000004100000410000000054111714455226020344 0ustar www-datawww-datacovers 'facets/time/hence' test_case Time do # We do not need to test #hence b/c it is an alias for #shift. # One test is provided to add to coverage report. method :hence do test do e = Time.utc(2008,11, 1, 18,30,57) r = Time.utc(2007,11, 1, 18,30,57).hence(1, :years) r.assert == e end end end facets-2.9.3/test/core/time/test_past.rb0000644000004100000410000000062711714455226020236 0ustar www-datawww-datacovers 'facets/time/past' test_case Time do method :past? do test do t = Time.now - 1000 t.assert.past? end test do n = Time.now + 1000 n.refute.past? end test do n = Time.now - 1001 t = Time.now - 1000 n.assert.past?(t) end test do n = Time.now - 999 t = Time.now - 1000 n.refute.past?(t) end end end facets-2.9.3/test/core/time/test_dst_adjustment.rb0000644000004100000410000000054411714455226022315 0ustar www-datawww-datacovers 'facets/time/dst_adjustment' test_case Time do # TODO: Is Time#dst_adjustment test correct? method :dst_adjustment do test do t0 = Time.utc(2010,01,20,12,00,00) t1 = Time.utc(2010,06,20,12,00,00) tt = t1.dst_adjustment(t0) tt.assert == t0 tt = t0.dst_adjustment(t1) tt.assert == t1 end end end facets-2.9.3/test/core/time/test_in.rb0000644000004100000410000000052611714455226017673 0ustar www-datawww-datacovers 'facets/time/ago' test_case Time do # We do not need to test #in b/c it is an alias for #shift. # One test is provided to add to coverage report. method :in do test do e = Time.utc(2008,11, 1, 18,30,57) r = Time.utc(2007,11, 1, 18,30,57).in(1, :years) r.assert == e end end end facets-2.9.3/test/core/time/test_shift.rb0000644000004100000410000000635611714455226020411 0ustar www-datawww-datacovers 'facets/time/shift' test_case Time do method :shift do setup "January 1st 2010 at Noon" do @t = Time.utc(2010,01,01, 12,00,00) end test 'years' do @t.shift(1, :year).year.assert = 2011 @t.shift(2, :years).year.assert = 2012 end test 'weeks' do @t.shift(1, :week).day.assert == 8 @t.shift(2, :weeks).day.assert == 15 end test 'days' do @t.shift(1, :day).day.assert == 2 @t.shift(2, :days).day.assert == 3 end test 'hours' do @t.shift(1, :hour).hour.assert == 13 @t.shift(2, :hours).hour.assert == 14 @t.shift(12, :hours).hour.assert == 0 end test 'minutes' do @t.shift(1, :minute).min.assert == 1 @t.shift(2, :minutes).min.assert == 2 @t.shift(60, :minutes).min.assert == 0 end test 'seconds' do @t.shift(1, :second).sec.assert == 1 @t.shift(2, :seconds).sec.assert == 2 @t.shift(60, :seconds).sec.assert == 0 end end method :shift do test "change years" do e = Time.utc(2008,11, 1, 18,30,57) r = Time.utc(2007,11, 1, 18,30,57).shift(1, :years) r.assert == e end test "change weeks" do e = Time.utc(2008,12, 1, 18,30,57) r = Time.utc(2008,11,24, 18,30,57).shift(1, :weeks) r.assert == e end test "change days" do e = Time.utc(2008,12, 1, 18,30,57) r = Time.utc(2008,11,30, 18,30,57).shift(1, :days) r.assert == e end test "change hours" do e = Time.utc(2008,12, 1, 0,30,57) r = Time.utc(2008,11,30, 23,30,57).shift(1, :hours) r.assert == e end test "change minutes" do e = Time.utc(2008,12, 1, 0, 0,57) r = Time.utc(2008,11,30, 23,58,57).shift(2, :minutes) r.assert == e end test "change seconds" do e = Time.utc(2008,12, 1, 0, 0, 1) r = Time.utc(2008,11,30, 23,59,57).shift(4, :seconds) r.assert == e end end # months are more difficult, so they get their own section method :shift do test "change month no year wrap" do e = Time.utc(2008,12, 1) r = Time.utc(2008,11, 1).shift(1, :months) r.assert == e end test "change month with year wrap due to month" do e = Time.utc(2008, 1, 1) r = Time.utc(2007,12, 1).shift(1, :months) r.assert == e end test "change month with 12 or more converts extra months into a year adjustment" do e = Time.utc(2008, 1, 1) r = Time.utc(2007, 1, 1).shift(12, :months) r.assert == e e = Time.utc(2008,12, 1) r = Time.utc(2006,11, 1).shift(25, :months) r.assert == e end test "change month with 12 or more AND year wrap due to month" do e = Time.utc(2008, 1, 1) r = Time.utc(2006,12, 1).shift(13, :months) r.assert == e end test "smaller units should remain unchanged" do e = Time.utc(2006, 1,20, 15,37,59) r = Time.utc(2005, 8,20, 15,37,59).shift(5, :months) r.assert == e end test "passing a negative number to #shift should be same as a positive number to #ago" do e = Time.utc(2005, 8,20) r = Time.utc(2006, 1,20).shift(-5, :months) r.assert == e r = Time.utc(2006, 1,20).ago(5, :months) r.assert == e end end end facets-2.9.3/test/core/time/test_change.rb0000644000004100000410000000037611714455226020515 0ustar www-datawww-datacovers 'facets/time/change' test_case Time do method :change do test do t = Time.local(2006,04,20,15,37) n = Time.now n = n.change(:month=>4, :day=>20, :hour=>15, :min=>37, :year=>2006) n.assert == t end end end facets-2.9.3/test/core/time/test_round_to.rb0000644000004100000410000000117411714455226021116 0ustar www-datawww-datacovers 'facets/time/round_to' test_case Time do method :round_to do setup do @t = Time.local(2000,03,03,3,37,23) end test "hour" do @t.round_to(60 * 60).assert == Time.local(2000,03,03,4, 0) end #test "month" do # @t.round_to(1.month).assert == Time.local(2000,03,03,3, 0) #end test "15 minutes" do @t.round_to(15 * 60).assert == Time.local(2000,03,03,3,30) end test "10 minutes" do @t.round_to(10 * 60).assert == Time.local(2000,03,03,3,40) end test "5 minutes" do @t.round_to(5 * 60).assert == Time.local(2000,03,03,3,35) end end end facets-2.9.3/test/core/time/test_less.rb0000644000004100000410000000653311714455226020237 0ustar www-datawww-datacovers 'facets/time/less' test_case Time do method :less do setup "January 20th 2010 at Noon" do @t = Time.utc(2010,01,20,12,00,00) end test 'years' do @t.less(1, :year).year.assert = 2009 @t.less(2, :years).year.assert = 2008 end test 'weeks' do @t.less(1, :week).day.assert == 13 @t.less(2, :weeks).day.assert == 6 end test 'days' do @t.less(1, :day).day.assert == 19 @t.less(2, :days).day.assert == 18 end test 'hours' do @t.less(1, :hour).hour.assert == 11 @t.less(2, :hours).hour.assert == 10 @t.less(12, :hours).hour.assert == 0 end test 'minutes' do @t.less(1, :minute).min.assert == 59 @t.less(2, :minutes).min.assert == 58 @t.less(60, :minutes).min.assert == 0 end test 'seconds' do @t.less(1, :second).sec.assert == 59 @t.less(2, :seconds).sec.assert == 58 @t.less(60, :seconds).sec.assert == 0 end end method :less do concern "verify via dates" test "change years" do e = Time.utc(2007,11, 1, 18,30,57) r = Time.utc(2008,11, 1, 18,30,57).less(1, :years) r.assert == e end test "change weeks" do e = Time.utc(2008,11,24, 18,30,57) r = Time.utc(2008,12, 1, 18,30,57).less(1, :weeks) r.assert == e end test "change days" do e = Time.utc(2008,11,30, 18,30,57) r = Time.utc(2008,12, 1, 18,30,57).less(1, :days) r.assert == e end test "change hours" do e = Time.utc(2008,11,30, 23,30,57) r = Time.utc(2008,12, 1, 0,30,57).less(1, :hours) r.assert == e end test "change minutes" do e = Time.utc(2008,11,30, 23,58,57) r = Time.utc(2008,12, 1, 0, 0,57).less(2, :minutes) r.assert == e end test "change seconds" do e = Time.utc(2008,11,30, 23,59,57) r = Time.utc(2008,12, 1, 0, 0, 1).less(4, :seconds) r.assert == e end end method :less do concern "months do not have a fixed duration" test "change month no year wrap" do e = Time.utc(2008,11, 1) r = Time.utc(2008,12, 1).less(1, :months) r.assert == e end test "change month with year wrap due to month" do e = Time.utc(2007,12, 1) r = Time.utc(2008, 1, 1).less(1, :months) r.assert == e end test "change month with 12 or more converts extra months into a year adjustment" do e = Time.utc(2007, 1, 1) r = Time.utc(2008, 1, 1).less(12, :months) r.assert == e e = Time.utc(2006,11, 1) r = Time.utc(2008,12, 1).less(25, :months) r.assert == e end # 13 months = 1 year + 1 month AND month changing from 12 to 1, # when going backward, means going back 1 extra year. test "change month with 12 or more AND year wrap due to month" do e = Time.utc(2006,12, 1) r = Time.utc(2008, 1, 1).less(13, :months) r.assert == e end test "smaller units should remain unchanged" do e = Time.utc(2005, 8,20, 15,37,59) r = Time.utc(2006, 1,20, 15,37,59).less(5, :months) r.assert == e end test "passing a negative number to #less should be same as a positive number to #shift" do e = Time.utc(2008, 1, 1) r = Time.utc(2006,12, 1).less(-13, :months) r.assert == e r = Time.utc(2006,12, 1).shift(13, :months) r.assert == e end end end facets-2.9.3/test/core/time/test_set.rb0000644000004100000410000000120111714455226020047 0ustar www-datawww-datacovers 'facets/time/set' test_case Time do method :set do setup do @t = Time.utc(2010,10,01,12,15,0) end test 'year' do x = @t.set(:year=>2020) x.year.assert == 2020 end test 'month' do x = @t.set(:month=>11) x.month.assert == 11 end test 'day' do x = @t.set(:day=>15) x.day.assert == 15 end test 'hours' do x = @t.set(:hour=>12) x.hour.assert == 12 end test 'minutes' do x = @t.set(:minutes=>12) x.min.assert == 12 end test 'seconds' do x = @t.set(:seconds=>9) x.sec.assert == 9 end end end facets-2.9.3/test/core/time/test_to_time.rb0000644000004100000410000000023611714455226020723 0ustar www-datawww-datacovers 'facets/time/to_time' test_case Time do method :to_time do test do t = Time.now t.to_time.assert.is_a?(Time) end end end facets-2.9.3/test/core/time/test_future.rb0000644000004100000410000000064311714455226020577 0ustar www-datawww-datacovers 'facets/time/future' test_case Time do method :future? do test do t = Time.now + 1000 t.assert.future? end test do n = Time.now - 1000 n.refute.future? end test do n = Time.now + 1001 t = Time.now + 1000 n.assert.future?(t) end test do n = Time.now + 999 t = Time.now + 1000 n.refute.future?(t) end end end facets-2.9.3/test/core/time/test_ago.rb0000644000004100000410000000054411714455226020033 0ustar www-datawww-datacovers 'facets/time/ago' test_case Time do # We do not need to test #ago b/c it is an alias for #less. # One test is provided to add to coverage report. method :ago do test "is an alias of #less" do t = Time.utc(2010,01,20,12,00,00) t.ago(1, :year).year.assert = 2009 t.ago(2, :years).year.assert = 2008 end end end facets-2.9.3/test/core/time/test_stamp.rb0000644000004100000410000000132711714455226020411 0ustar www-datawww-datacovers 'facets/time/stamp' test_case Time do method :stamp do test "default" do t = Time.utc(2005,4,20,15,37) t.stamp.assert == "2005-04-20 15:37:00 +0000" end test "ruby18" do t = Time.utc(2005,4,20,15,37) t.stamp(:ruby18).assert == "Wed Apr 20 15:37:00 +0000 2005" end test "long format" do t = Time.utc(2005,4,20,15,37) t.stamp(:long).assert == "April 20, 2005 15:37" end test "short format" do t = Time.utc(2005,4,20,15,37) t.stamp(:short).assert == "20 Apr 15:37" end end class_method :stamp do test "long format" do Time.stamp(:long) end test "short format" do Time.stamp(:short) end end end facets-2.9.3/test/core/module/0000755000004100000410000000000011714455226016225 5ustar www-datawww-datafacets-2.9.3/test/core/module/test_integrate.rb0000644000004100000410000000053511714455226021576 0ustar www-datawww-datacovers 'facets/module/integrate' test_case Module do method :integrate do test do m = Module.new do def x ; 1 ; end end c = Class.new do integrate m do rename :y, :x end end ic = c.new NoMethodError.assert.raised?{ ic.x } ic.y.assert == 1 end end end facets-2.9.3/test/core/module/test_class_def.rb0000644000004100000410000000047411714455226021541 0ustar www-datawww-datacovers 'facets/module/class_def' test_case Module do method :class_def do test do m = Module.new m.class_def(:x){"x"} c = Class.new{ include m } c.new.x.assert == "x" end test do c = Class.new c.class_def(:x){"x"} c.new.x.assert == "x" end end end facets-2.9.3/test/core/module/test_abstract.rb0000644000004100000410000000061311714455226021414 0ustar www-datawww-datacovers 'facets/module/abstract' test_case Module do method :abstract do test "in a module" do m = Module.new{ abstract :q } c = Class.new{ include m } x = c.new TypeError.assert.raised?{ x.q } end test "in a class" do c = Class.new{ abstract :q } #c.pry.abstract :q x = c.new TypeError.assert.raised?{ x.q } end end end facets-2.9.3/test/core/module/test_method_clash.rb0000644000004100000410000000176511714455226022254 0ustar www-datawww-datacovers 'facets/module/method_clash' test_case Module do setup do @x = Class.new do def q1; "q1"; end def x1; "x1"; end def r1; "r1"; end private def q2; "q2"; end def x2; "x1"; end protected def q3; "q3"; end def x3; "x3"; end end @y = Class.new do def q1; "q1"; end def y1; "y1"; end private def q2; "q2"; end def y2; "y2"; end def r1; "r1"; end protected def q3; "q3"; end def y3; "y3"; end end @z = Class.new end method :method_clash? do test do @x.assert.method_clash?(@y) @y.assert.method_clash?(@x) @z.refute.method_clash?(@x) @x.refute.method_clash?(@z) end end method :method_clash do test do c = @x.method_clash(@y) c.map!{ |m| m.to_s } %w{r1 q1 q2 q3}.each do |x| c.assert.include?(x) end %w{x1 x2 x3 y1 y2 y3}.each do |x| c.refute.include?(x) end end end end facets-2.9.3/test/core/module/test_instance_method.rb0000644000004100000410000000044511714455226022760 0ustar www-datawww-datacovers 'facets/module/instance_method' test_case Module do method :instance_method! do test do c = Class.new do def x; "x"; end end x1 = c.instance_method!(:x) x2 = c.instance_method!(:x) x1.object_id.assert == x2.object_id end end end facets-2.9.3/test/core/module/test_alias_module_function.rb0000644000004100000410000000053311714455226024155 0ustar www-datawww-datacovers 'facets/module/alias_module_function' test_case Module do method :alias_module_function do test do m = Module.new do def x ; 33 ; end module_function :x alias_module_function :y, :x end m.y.assert == 33 # use send b/c private? #@m.send(:y).assert == 33 end end end facets-2.9.3/test/core/module/test_alias_method_chain.rb0000644000004100000410000000100511714455226023400 0ustar www-datawww-datacovers 'facets/module/alias_method_chain' test_case Module do method :alias_method_chain do test do x = Module.new do def self.included(base) base.module_eval { alias_method_chain :foo, :feature } end def foo_with_feature foo_without_feature + '!' end end y = Class.new do def foo "FOO" end include x end iy = y.new iy.foo.assert == "FOO!" end end end facets-2.9.3/test/core/module/test_attr_setter.rb0000644000004100000410000000057411714455226022157 0ustar www-datawww-datacovers 'facets/module/attr_setter' test_case Module do method :attr_setter do test do c = Class.new do attr_setter :a end x = c.new x.a(1) x.a.assert == 1 end test do c = Class.new do attr_setter :a alias_setter :b, :a end x = c.new x.b(1) x.a.assert == 1 end end end facets-2.9.3/test/core/module/test_modname.rb0000644000004100000410000000023311714455226021227 0ustar www-datawww-datacovers 'facets/module/modname' test_case Module do method :modname do test do Lemon::TestCase.modname.assert == "Lemon" end end end facets-2.9.3/test/core/module/test_ancestor.rb0000644000004100000410000000027311714455226021431 0ustar www-datawww-datacovers 'facets/module/ancestor' test_case Module do method :ancestor? do test do c1 = Class.new c2 = Class.new(c1) c2.assert.ancestor?(c1) end end end facets-2.9.3/test/core/module/test_redefine_method.rb0000644000004100000410000000062211714455226022732 0ustar www-datawww-datacovers 'facets/module/redefine_method' test_case Module do method :redefine_method do test do c = Class.new do def a; "a"; end redefine_method(:a){ nil } end c.new.a.assert == nil end end method :redef do test do c = Class.new do def b; "b"; end redef(:b){ "x" } end c.new.b.assert == "x" end end end facets-2.9.3/test/core/module/test_basename.rb0000644000004100000410000000024211714455226021362 0ustar www-datawww-datacovers 'facets/module/basename' test_case Module do method :basename do test do Lemon::TestCase.basename.assert == "TestCase" end end end facets-2.9.3/test/core/module/test_revise.rb0000644000004100000410000000152511714455226021111 0ustar www-datawww-datacovers 'facets/module/revise' test_case Module do method :revisal do test do m = Module.new do def x ; 1 ; end end c = Class.new do include m.revisal { rename :y, :x } end ic = c.new ic.y.assert == 1 NoMethodError.assert.raised?{ ic.x } end end method :revise do test do m = Module.new do def x ; 1 ; end end c = Class.new do include m.revise { rename :y, :x } end ic = c.new ic.y.assert == 1 NoMethodError.assert.raised?{ ic.x } end end method :remove do test do c = Class.new do def the_removed_method ; 'not here' ; end remove :the_removed_method end c.new.refute.respond_to?(:the_removed_method) end end end facets-2.9.3/test/core/module/test_methodize.rb0000644000004100000410000000044211714455226021601 0ustar www-datawww-datacovers 'facets/module/methodize' test_case Module do method :methodize do test do Lemon.methodize.assert == 'lemon' end end end test_case Class do method :methodize do test do Lemon::TestCase.methodize.assert == 'lemon__test_case' end end end facets-2.9.3/test/core/module/test_spacename.rb0000644000004100000410000000033511714455226021546 0ustar www-datawww-datacovers 'facets/module/spacename' test_case Module do method :spacename do test do Lemon::TestCase.spacename.assert == 'Lemon' Lemon.spacename.assert == '' # should this be nil ? end end end facets-2.9.3/test/core/module/test_alias_accessor.rb0000644000004100000410000000053711714455226022571 0ustar www-datawww-datacovers 'facets/module/alias_accessor' test_case Module do method :alias_accessor do test do c = Class.new do attr_accessor :x alias_accessor :y, :x end x = c.new x.x = 10 x.x.assert == 10 x.y.assert == 10 x.y = 20 x.x.assert == 20 x.y.assert == 20 end end end facets-2.9.3/test/core/module/test_enclosure.rb0000644000004100000410000000061611714455226021613 0ustar www-datawww-datacovers 'facets/module/enclosure' covers 'facets/module/enclosures' test_case Module do method :enclosure do test do Lemon::TestCase.enclosure.assert == Lemon end test "anonymous module" do m = Module.new m.enclosure.assert == Object end end method :enclosures do test do Lemon::TestCase.enclosures.assert == [Lemon, Object] end end end facets-2.9.3/test/core/module/test_can.rb0000644000004100000410000000035011714455226020350 0ustar www-datawww-datacovers 'facets/module/can' test_case Module do method :can do test do m = Module.new do def x; "x"; end end c = Class.new do can m end c.x.assert == "x" end end end facets-2.9.3/test/core/module/test_all_instance_methods.rb0000644000004100000410000000072711714455226023776 0ustar www-datawww-datacovers 'facets/module/all_instance_methods' test_case Module do method :all_instance_methods do test do c = Class.new do def x; "x"; end private def y; "y"; end protected def z; "z"; end end list = c.all_instance_methods(false) list.map!{ |m| m.to_sym } # b/c of diff in 1.8 vs 1.9 list.assert.include?(:x) list.assert.include?(:y) list.assert.include?(:z) end end end facets-2.9.3/test/core/module/test_module_def.rb0000644000004100000410000000050011714455226021707 0ustar www-datawww-datacovers 'facets/module/module_def' test_case Module do method :module_def do test do m = Module.new m.module_def(:x){"x"} c = Class.new{ include m } c.new.x.assert == "x" end test do c = Class.new c.module_def(:x){"x"} c.new.x.assert == "x" end end end facets-2.9.3/test/core/module/test_anonymous.rb0000644000004100000410000000032211714455226021636 0ustar www-datawww-datacovers 'facets/module/anonymous' test_case Module do method :anonymous? do test do m = Module.new m.assert.anonymous? end test do Lemon.refute.anonymous? end end end facets-2.9.3/test/core/module/test_method_space.rb0000644000004100000410000000225611714455226022251 0ustar www-datawww-datacovers 'facets/module/method_space' test_case Class do method :method_space do test "via a block" do c = Class.new do def x; "x"; end method_space :s do def x; "sx"; end end end o = c.new o.x.assert == 'x' o.s.x.assert == 'sx' end test "via module" do M = Module.new do def x; "mx"; end end c = Class.new do def x; "x"; end method_space M end o = c.new o.x.assert == 'x' o.m.x.assert == 'mx' end test "instance method is not defined" do c = Class.new do method_space :s do def x; "sx"; end end end o = c.new expect(NoMethodError){ c.x } end end method :include_as do setup do m = Module.new do def x; "x"; end def y; @y; end end @c = Class.new do include_as :m => m def initialize @y = "y" end end end test "provides method space" do o = @c.new o.m.x.assert == "x" end test "has access to instance scope" do o = @c.new o.m.y.assert == "y" end end end facets-2.9.3/test/core/module/test_class_extend.rb0000644000004100000410000000272111714455226022267 0ustar www-datawww-datacovers 'facets/module/class_extend' test_case Module do method :class_extend do setup "module using class_extend" do @mod = Module.new do def i ; end class_extend do def n ; 42 ; end def s ; self ; end end end end test "extends module" do @mod.n.assert == 42 @mod.s.assert == @mod end test "has expected methods" do @mod.instance_methods.map{ |m| m.to_s }.assert == ['i'] end test "transfers class methods to including class" do mod = @mod mod = Module.new do include mod end mod.n.assert == 42 mod.s.assert == mod end test "doesn't overwrite instance methods" do mod = @mod c = Class.new do include mod def n ; 11 ; end end c.new.n.assert == 11 end test "is overridable via including module" do mod = @mod m = Module.new do include mod class_extend do def n ; super + 1 ; end end end m.n.assert == 43 # notice the difference! m.s.assert == m end test "transfers class methods thru multiple levels of include" do mod = @mod a = Module.new do include mod class_extend do def n ; super + 1 ; end end end m = Module.new do include a end m.n.assert == 43 m.s.assert == m end end end facets-2.9.3/test/core/module/test_rename_method.rb0000644000004100000410000000073611714455226022426 0ustar www-datawww-datacovers 'facets/module/rename_method' test_case Module do method :rename_method do test do c = Class.new do def a; "A" ; end rename_method :b, :a end c.new.refute.respond_to?(:a) c.new.assert.respond_to?(:b) end end method :rename do test do c = Class.new do def c; "C" ; end rename :d, :c end c.new.refute.respond_to?(:c) c.new.assert.respond_to?(:d) end end end facets-2.9.3/test/core/module/test_redirect_method.rb0000644000004100000410000000063211714455226022753 0ustar www-datawww-datacovers 'facets/module/redirect_method' test_case Module do method :redirect_method do test do c = Class.new do def a1 ; 1 ; end redirect_method :a2 => :a1 end c.new.a2.assert == 1 end end method :redirect do test do c = Class.new do def b1 ; 1 ; end redirect :b2 => :b1 end c.new.b2.assert == 1 end end end facets-2.9.3/test/core/module/test_pathize.rb0000644000004100000410000000042611714455226021257 0ustar www-datawww-datacovers 'facets/module/pathize' test_case Module do method :pathize do test do Lemon.pathize.assert == 'lemon' end end end test_case Class do method :pathize do test do Lemon::TestCase.pathize.assert == 'lemon/test_case' end end end facets-2.9.3/test/core/module/test_to_obj.rb0000644000004100000410000000037711714455226021074 0ustar www-datawww-datacovers 'facets/module/to_obj' test_case Module do method :to_obj do test do m = Module.new do def x; "x"; end def y; "y"; end end o = m.to_obj o.x.assert == "x" o.y.assert == "y" end end end facets-2.9.3/test/core/module/test_copy_inheritor.rb0000644000004100000410000000110611714455226022644 0ustar www-datawww-datacovers 'facets/module/copy_inheritor' test_case Module do method :copy_inheritor do setup do m1 = Module.new do copy_inheritor :koko, [] koko << 1 end c1 = Class.new do include m1 #inheritor :koko, [], :+ koko << 2 koko << 3 end c2 = Class.new do include m1 #inheritor :koko, [], :+ koko << 4 end @m1, @c1, @c2 = m1, c1, c2 end test do @m1.koko.assert == [1] @c1.koko.assert == [1,2,3] @c2.koko.assert == [1,4] end end end facets-2.9.3/test/core/module/test_instance_function.rb0000644000004100000410000000076411714455226023331 0ustar www-datawww-datacovers 'facets/module/instance_function' test_case Module do method :instance_function do setup "using instance_function" do @m = Module.new do instance_function def self.jumble(obj, arg) obj + arg end end end test "class method" do r = @m.jumble('Try', 'Me') r.assert == 'TryMe' end test "instance method" do s = 'Try' s.extend @m r = s.jumble('Me') r.assert == 'TryMe' end end end facets-2.9.3/test/core/module/test_module_load.rb0000644000004100000410000000050311714455226022073 0ustar www-datawww-datacovers 'facets/module/module_load' test_case Module do # TODO: write tests for module_load skip "need to use a ruby fixture file to test module_load.rb" do method :module_load do end method :module_require do end method :class_load do end method :class_require do end end end facets-2.9.3/test/core/module/test_memoize.rb0000644000004100000410000000102111714455226021250 0ustar www-datawww-datacovers 'facets/module/memoize' test_case Module do method :memoize do test do tc = Class.new do def initialize(a) @a = a end def a "#{@a ^ 3 + 4}" end memoize :a end t1 = tc.new(1) t2 = tc.new(2) t3 = tc.new(3) t1.a.assert == "6" t2.a.assert == "5" t3.a.assert == "4" t1.a.__id__.assert == t1.a.__id__ t2.a.__id__.assert == t2.a.__id__ t3.a.__id__.assert == t3.a.__id__ end end end facets-2.9.3/test/core/module/test_nodef.rb0000644000004100000410000000043011714455226020701 0ustar www-datawww-datacovers 'facets/module/nodef' test_case Module do method :nodef do test do c = Class.new do def the_undefined_method ; 'not here' ; end nodef :the_undefined_method end c.new.refute.respond_to?(:the_undefined_method) end end end facets-2.9.3/test/core/module/test_op.rb0000644000004100000410000000130311714455226020224 0ustar www-datawww-datacovers 'facets/module/op.rb' test_case Module do setup do @a = Module.new do def x; "x"; end def z; "zA"; end end @b = Module.new do def y; "y"; end def z; "zB"; end end end method :+ do test do q = @a + @b q.extend q q.x.assert == "x" q.y.assert == "y" q.z.assert == "zB" end end method :- do test do r = @a - @b r.extend r r.x.assert == "x" NoMethodError.assert.raised?{ r.z } end end method :* do test do z = @a * { :x => :y } z.extend z z.y.assert == "x" z.z.assert == "zA" NoMethodError.assert.raised?{ z.x } end end end facets-2.9.3/test/core/module/test_is.rb0000644000004100000410000000140711714455226020226 0ustar www-datawww-datacovers 'facets/module/is' test_case Module do method :is? do test do m = Module.new x = Class.new y = Class.new(x) do is m end y.assert.is?(x) y.assert.is?(m) end end method :is do test do m = Module.new do def q; "q"; end end x = Class.new do is m end x.new.q.assert == "q" end # Note, we dynamically set the Self constant to avoid a named module # showing up as an uncovered namespace in the Lemon coverage report. test do m = Module.new do s = Module.new do def q; "q"; end end const_set('Self', s) end x = Class.new do is m end x.q.assert == "q" end end end facets-2.9.3/test/core/module/test_instance_method_defined.rb0000644000004100000410000000115711714455226024437 0ustar www-datawww-datacovers 'facets/module/instance_method_defined' test_case Module do method :instance_method_defined? do test do c = Class.new do def x; "x"; end end c.assert.instance_method_defined?(:x) end end method :singleton_method_defined? do test do c = Class.new do def self.x; "x"; end end c.assert.singleton_method_defined?(:x) end end method :module_method_defined? do test "alias for #singleton_method_defined" do c = Class.new do def self.x; "x"; end end c.assert.module_method_defined?(:x) end end end facets-2.9.3/test/core/module/test_set.rb0000644000004100000410000000054411714455226020407 0ustar www-datawww-datacovers 'facets/module/set' test_case Module do method :set do test do c = Class.new do set :x, 10 end c.x.assert == 10 end test do h = 1 c = Class.new do set :x do h += 1 end end c.x.assert == 2 c.x.assert == 3 c.x.assert == 4 end end end facets-2.9.3/test/core/module/test_wrap_method.rb0000644000004100000410000000065411714455226022127 0ustar www-datawww-datacovers 'facets/module/wrap_method' test_case Module do method :wrap_method do test do c = Class.new do def a; "A"; end wrap_method(:a) { |old| old.call + "B" } end c.new.a.assert == "AB" end end method :wrap do test do c = Class.new do def b; "B"; end wrap(:b) { |old| old.call + "C" } end c.new.b.assert == "BC" end end end facets-2.9.3/test/core/module/test_class_inheritor.rb0000644000004100000410000000474411714455226023012 0ustar www-datawww-datacovers 'facets/module/class_inheritor' test_case Class do method :class_inheritor do test "subclass with inheritor" do c1 = Class.new do class_inheritor :koko, [], :+ koko! << 1 end c2 = Class.new(c1) do class_inheritor :koko, [], :+ koko! << 2 end c1.koko!.assert == [1] c1.koko.assert == [1] c2.koko!.assert == [2] c2.koko.assert == [1,2] end test "subclass without inheritor" do c1 = Class.new do class_inheritor :koko, [], :+ koko! << 1 end c2 = Class.new(c1) c1.koko!.assert == [1] c1.koko.assert == [1] c2.koko!.assert == [] c2.koko.assert == [1] end test "include module with inheritor" do c1 = Class.new do class_inheritor :x, {}, :merge x![:a] = 1 end m1 = Module.new do class_inheritor :x, {}, :merge x![:b] = 2 end c2 = Class.new(c1) do include m1 class_inheritor :x, {}, :merge x![:c] = 3 end c1.x.assert == {:a=>1} m1.x[:b].assert == 2 c2.x.assert == {:a=>1,:b=>2,:c=>3} c1.x[:a].assert == 1 c1.x[:b].assert == nil c1.x[:c].assert == nil c2.x[:a].assert == 1 c2.x[:b].assert == 2 c2.x[:c].assert == 3 c2.x![:d] = 4 c2.x[:d].assert == 4 end test "using #concat as the inheritor operator" do c1 = Class.new do class_inheritor :relations, [], :concat end c2 = Class.new(c1) do #class_inheritor :relations, [], :concat end c1.relations! << 1 c1.relations! << 2 c2.relations! << 3 c1.relations.assert == [1,2] c2.relations.assert == [1,2,3] end end end test_case Module do method :class_inheritor do test do m1 = Module.new do class_inheritor :koko, [], :+ koko! << 1 end c1 = Class.new do include m1 #inheritor :koko, [], :+ koko! << 2 koko! << 3 end c2 = Class.new do include m1 #inheritor :koko, [], :+ koko! << 4 end m1.koko.assert == [1] c1.koko.assert == [1,2,3] c2.koko.assert == [1,4] end end end =begin Test.class Inheritor do setup do a = [1] @i = Inheritor.new(a, [2], :+) end method :== do test do @i.assert == [2] end end method :inheritance do test do @i.inheritance == [1,2] end end end =end facets-2.9.3/test/core/module/test_class.rb0000644000004100000410000000046111714455226020717 0ustar www-datawww-datacovers 'facets/module/class' test_case Module do method :class? do test do x_class = Class.new y_class = Class.new(x_class) x = x_class.new y = y_class.new x_class.assert.class?(x) y_class.assert.class?(y) y_class.assert.class?(y) end end end facets-2.9.3/test/core/module/test_preextend.rb0000644000004100000410000000053011714455226021605 0ustar www-datawww-datacovers 'facets/module/preextend' test_case Module do method :preextend do test "module method" do m = Module.new do def q; "qm"; end end n = Module.new do preextend m def q; "qn"; end end x = Class.new do include n end n.q.assert == "qm" end end end facets-2.9.3/test/core/module/test_remove.rb0000644000004100000410000000042411714455226021106 0ustar www-datawww-datacovers 'facets/module/remove' test_case Module do method :remove do test do c = Class.new do def the_removed_method ; 'not here' ; end remove :the_removed_method end c.new.refute.respond_to?(:the_removed_method) end end end facets-2.9.3/test/standard/0000755000004100000410000000000011714455227015611 5ustar www-datawww-datafacets-2.9.3/test/standard/math/0000755000004100000410000000000011714455226016541 5ustar www-datawww-datafacets-2.9.3/test/standard/math/test_sign.rb0000644000004100000410000000032611714455226021066 0ustar www-datawww-datarequire 'facets/math/sign' test_case Math do class_method :sign do test do Math.sign(-3.1).assert == -1.0 Math.sign( 0.0).assert == 0.0 Math.sign( 3.1).assert == 1.0 end end end facets-2.9.3/test/standard/math/test_median.rb0000644000004100000410000000043311714455226021362 0ustar www-datawww-datacovers 'facets/math/median' test_case Math do class_method :median do test "fractional" do r = Math.median [1, 2, 3, 3, 6, 11, 20, 20] r.assert == 4.5 end test "whole value" do r = Math.median [1, 2, 4, 6, 8] r.assert == 4 end end end facets-2.9.3/test/standard/math/test_percentile.rb0000644000004100000410000000030311714455226022253 0ustar www-datawww-datacovers 'facets/math/percentile' test_case Math do class_method :percentile do test do a = [1,1,2,2,3,3,3,4] r = Math.percentile(a,75) r.assert == 3.0 end end end facets-2.9.3/test/standard/math/test_abs.rb0000644000004100000410000000031511714455226020671 0ustar www-datawww-datarequire 'facets/math/abs' test_case Math do class_method :abs do test do Math.abs(-3.1).assert == 3.1 Math.abs( 0.0).assert == 0.0 Math.abs( 3.1).assert == 3.1 end end end facets-2.9.3/test/standard/test_tuple.rb0000644000004100000410000000212411714455227020325 0ustar www-datawww-datacovers 'facets/tuple' test_case Tuple do class_method :[] do test "tuples with same content are the same object" do t1 = Tuple[1,2,3] t2 = Tuple[1,2,3] t1.object_id.assert == t2.object_id end end method :< do test do t1 = Tuple[1,2,3] t2 = Tuple[2,4,5] t1.assert < t2 end end method :> do test do t1 = Tuple[1,2,3] t2 = Tuple[2,4,5] t2.assert > t1 end end method :to_a do test do t1 = Tuple[1,2,3] a1 = t1.to_a assert( Array === a1 ) end end method :<< do test do t1 = Tuple[1,2,3] t1 = t1 << 4 t1.assert.is_a? Tuple t2 = Tuple[1,2,3,4] t1.object_id.assert == t2.object_id end end end test_case String do method :to_t do test do t1 = "1.2.3".to_t t1.assert.is_a? Tuple t2 = Tuple[1,2,3] t1.object_id.assert == t2.object_id end test do t1 = "1.2.3a".to_t t1.assert.is_a? Tuple t2 = Tuple[1,2,'3a'] t1.assert == t2 t1.object_id.assert == t2.object_id end end end facets-2.9.3/test/standard/test_instantiable.rb0000644000004100000410000000074011714455227021653 0ustar www-datawww-datarequire 'facets/instantiable' test_case Instantiable do setup do @m = Module.new do extend Instantiable attr :a def initialize( a ) @a = a end end @n = Module.new do include Instantiable attr :a def initialize( a ) @a = a end end end method :new do test do m = @m.new(1) 1.assert == m.a end test do m = @n.new(1) 1.assert == m.a end end end facets-2.9.3/test/standard/test_random.rb0000644000004100000410000001026711714455227020463 0ustar www-datawww-datacovers 'facets/random' test_case Random do class_method :letter do test do 100.times { |i| /[a-zA-z]/.assert =~ Random.letter } end end end test_case Range do # helper method def assert_at_rand_table(table) table.each do |x, y| 20.times do x.at_rand.assert == y end end end # helper method def assert_random_range(range) 20.times do range.assert.include?( range.at_rand ) end end method :at_rand do test "within range" do list = [ 1..4, 1...4, 1.5..2.5, 1.5...2.5, -4..-1, -4...-1, -2.5..-1.5, -2.5...-1.5, 'a'..'d', 'a'...'d' ] list.each{ |rng| assert_random_range(rng) } end test "within range special cases" do assert_at_rand_table( (5..5) => 5, (5...5) => nil, (5..-1) => nil, (5.0..5.0) => 5.0, (5.0...5.0) => nil, (5.0...-1.0) => nil ) end test "reverse ranges" do assert_at_rand_table( (4..1) => nil, (4...1) => nil, (-1..-4) => nil, (-1...-4) => nil ) #assert((1..4).include?((4..1).at_rand)) #assert((-4...-1).include?((-1...-4).at_rand)) #assert((-4..-1).include?((-1..-4).at_rand)) end # I'd rather it return the first sentinel than +nil+. # Really, ruby should be raising an error as an invalid range value. test "exclusive range" do (5...5).at_rand.assert == nil #expect RangeError do # (5...5).at_rand #end end end end test_case Array do method :at_rand do test do a = [1,2,3,4,5] 20.times{ a.assert.include?( a.at_rand ) } end end method :at_rand! do test do a = ['a','b','c'] a.at_rand!.length.assert == 1 a.length.assert == 2 end end method :pick do test do a = ['a','b','c'] a.pick(3).length.assert == 3 a.length.assert == 3 a = ['a','b','c'] a.pick(4).length.assert == 3 a.length.assert == 3 end end method :pick! do test do a = ['a','b','c'] a.pick!(3).length.assert == 3 a.length.assert == 0 a = ['a','b','c'] a.pick!(4).length.assert == 3 a.length.assert == 0 end end method :rand_index do test do 10.times { i = [1,2,3].rand_index (0..2).assert.include?(i) } end end method :rand_subset do test do 10.times { a = [1,2,3,4].rand_subset a.size.assert <= 4 } end end method :shuffle do test do a = [1,2,3,4,5] b = a.shuffle b.sort.assert == a end end method :shuffle! do test do a = [1,2,3,4,5] b = a.dup b.shuffle! b.sort.assert == a end end end test_case Hash do method :rand_key do test do h = { :a=>1, :b=>2, :c=>3 } 10.times { h.keys.assert.include?( h.rand_key ) } end end method :rand_pair do test do h = { :a=>1, :b=>2, :c=>3 } 10.times { k,v = *h.rand_pair; h[k].assert == v } end end method :rand_value do test do h = { :a=>1, :b=>2, :c=>3 } 10.times { h.values.assert.include?( h.rand_value ) } end end method :shuffle do test do h = {:a=>1, :b=>2, :c=>3 } h.shuffle end end method :shuffle! do test do h = {:a=>1, :b=>2, :c=>3 } h.shuffle! end end end test_case String do method :at_rand do test do a = '12345' 20.times{ a.assert.include?( a.at_rand ) } end end method :at_rand! do test do x = 'ab' r = x.at_rand! assert( r == 'a' || r == 'b' ) assert( x == 'a' || x == 'b' ) end end method :rand_index do test do 10.times{ (0..2).assert.include?( 'abc'.rand_index ) } end end method :rand_byte do test do 2.times do s = 'ab' r = s.rand_byte if RUBY_VERSION > '1.9' assert( r == 'a' || r == 'b' ) else assert( r == 97 || r == 98 ) end end end end method :shuffle do test do "abc 123".shuffle #"abc 123".shuffle! end end method :shuffle! do test do "abc 123".shuffle! end end end facets-2.9.3/test/standard/test_enumargs.rb0000644000004100000410000000275011714455227021022 0ustar www-datawww-datacovers 'facets/enumargs' test_case Enumerable::Arguments do setup do @PlusArray = Class.new do include Enumerable::Arguments def initialize(arr) @arr = arr end def each(n=0) @arr.each{ |e| yield(e+n) } end end end method :collect do test do t = @PlusArray.new([1,2,3]) r = t.collect(4){ |e| e } r.assert == [5,6,7] end end #method :each_slice do # test do # t = PlusArray.new([1,2,3,4]) # a = [] # t.each_slice(2,4){ |e,f| a << [e,f] } # a.assert == [[5,6],[7,8]] # end #end #method :find do # test do # t = PlusArray.new([1,2,3,4]) # f = t.find(2, :ifnone=>lambda{:NOPE}) { |a| a == 10 } # f.assert == :NOPE # end #end method :grep do end method :to_a do test do t = @PlusArray.new([1,2,3]) t.to_a(4).assert == [5,6,7] end end method :min do test do t = @PlusArray.new([1,2,3]) t.min(4).assert = 5 end end method :max do test do t = @PlusArray.new([1,2,3]) t.max(4).assert == 7 end end method :include? do test do t = @PlusArray.new([1,2,3]) t.assert.include?(7,4) end end method :select do test do t = @PlusArray.new([1,2,3]) r = t.select(4){ |x| x == 6 } r.assert == [6] end end method :reject do test do t = @PlusArray.new([1,2,3]) r = t.reject(4){ |x| x == 6 } r.assert == [5,7] end end end facets-2.9.3/test/standard/test_timer.rb0000644000004100000410000000206311714455227020316 0ustar www-datawww-datacovers 'facets/timer' test_case Timer do class_method :time do test "can keep time of a block" do Timer.time do |timer| timer.total_time.round.assert == 0 sleep 1 timer.total_time.round.assert == 1 end end test "can be stopped" do Timer.time do |timer| sleep 0.4 timer.stop sleep 0.6 timer.total_time.round.assert == 0 end end test "timer can be started again" do Timer.time do |timer| timer.stop sleep 0.5 timer.total_time.round.assert == 0 timer.start sleep 1 timer.total_time.round.assert == 1 end end end method :start do test "out of time" do t = Timer.new(0.5) expect TimeoutError do t.start sleep 1 t.stop end end test "in time" do t = Timer.new(2) t.start sleep 0.5 t.stop end end method :stop do test "in time" do t = Timer.new(2) t.start sleep 0.5 t.stop end end end facets-2.9.3/test/standard/test_multipliers.rb0000644000004100000410000000341611714455227021552 0ustar www-datawww-datacovers 'facets/multipliers' test_case Fixnum do method :deka do test do 1.deka.assert == 10 end end method :hecto do test do 1.hecto.assert == 100 end end method :kilo do test do 1.kilo.assert == 1000 end end method :mega do test do 1.mega.assert == 1000000 end end method :giga do test do 1.giga.assert == 1000000000 end end method :tera do test do 1.tera.assert == 1000000000000 end end method :peta do test do 1.peta.assert == 1000000000000000 end end method :exa do test do 1.exa.assert == 1000000000000000000 end end # Fractional method :deci do test do 1.deci.assert == 0.1 end end method :centi do test do 1.centi.assert == 0.01 end end method :milli do test do 1.milli.assert == 0.001 end end method :micro do test do 1.micro.assert == 0.000001 end end method :nano do test do 1.nano.assert == 0.000000001 end end method :pico do test do 1.pico.assert == 0.000000000001 end end method :femto do test do 1.femto.assert == 0.000000000000001 end end method :atto do test do 1.atto.assert == 0.000000000000000001 end end # SI Binary method :kibi do test do 1.kibi.assert == 1024 end end method :mebi do test do 1.mebi.assert == 1024**2 end end method :gibi do test do 1.gibi.assert == 1024**3 end end method :tebi do test do 1.tebi.assert == 1024**4 end end method :pebi do test do 1.pebi.assert == 1024**5 end end method :exbi do test do 1.exbi.assert == 1024**6 end end end facets-2.9.3/test/standard/test_shellwords.rb0000644000004100000410000000244311714455227021366 0ustar www-datawww-datacovers 'facets/shellwords' test_case Shellwords do class_method :shellwords do test do cmd = "ruby my_prog.rb | less" Shellwords.shellwords(cmd).assert.instance_of?(Array) Shellwords.shellwords(cmd).length.assert == 4 end test "unmatched double quote" do bad_cmd = 'one two "three' expect ArgumentError do Shellwords.shellwords(bad_cmd) end end test "unmatched single quote" do bad_cmd = "one two 'three" expect ArgumentError do Shellwords.shellwords(bad_cmd) end end test "unmatched quotes" do bad_cmd = "one '"'"''""'"" expect ArgumentError do Shellwords.shellwords(bad_cmd) end end end end test_case Array do method :shellwords do test do e = ["a", "b"] a = ["a", "b"].shellwords a.assert == e end test do e = ["-d", "a", "b"] a = ["a", "b", {:d=>true}].shellwords a.assert == e end end end test_case Hash do method :shellwords do test do e = ['--debug'] a = {:debug=>true}.shellwords a.assert == e end test do e = ['--name="jim"', '--debug'] a = {:debug=>true, :name=>"jim"}.shellwords a.each do |x| e.assert.include?(x) end end end end facets-2.9.3/test/standard/test_memoizable.rb0000644000004100000410000000127511714455227021326 0ustar www-datawww-datacovers 'facets/memoizable' test_case Memoizable do method :memoize do test "returns expected values" do c = Class.new do include Memoizable def initialize(a) @a = a end attr_accessor :a memoize :a end o = c.new("A") o.a.assert == "A" o.a = "B" o.a.assert == "A" end test "returns identical objects" do c = Class.new do include Memoizable def initialize(a) @a = a end attr_accessor :a memoize :a end o = c.new("A") o.a.__id__.assert == o.a.__id__ o.a = "B" o.a.__id__.assert == o.a.__id__ end end end facets-2.9.3/test/standard/test_ostruct.rb0000644000004100000410000000751311714455227020706 0ustar www-datawww-datacovers 'facets/ostruct' test_case OpenStruct do method :__update__ do test do o = OpenStruct.new(:a => 1) h = { :b => 2 } o.__update__(h) o.b.assert == 2 end test do o = OpenStruct.new( { :a => 1 } ) h = { :b => 2 } o.__update__(h) o.b.assert == 2 end end method :__merge__ do test do o = OpenStruct.new( { :a => 1 } ) h = { :b => 2 } q = o.__merge__( h ) q.a.assert == 1 q.b.assert == 2 end test do o1 = OpenStruct.new( { :a => 1 } ) o2 = OpenStruct.new( { :b => 2 } ) q = o1.__merge__( o2 ) q.a.assert == 1 q.b.assert == 2 end test "with_hash" do o = OpenStruct.new( { :a => 1 } ) h = { :b => 2 } q = o.__merge__(h) q.a.assert == 1 q.b.assert == 2 end test "two open structs" do o1 = OpenStruct.new( { :a => 1 } ) o2 = OpenStruct.new( { :b => 2 } ) q = o1.__merge__(o2) q.a.assert == 1 q.b.assert == 2 end end method :instance_delegate do test "store" do o = OpenStruct.new(:a => 1) o.instance_delegate.store(:a,1) o.a.assert == 1 end test "update" do o = OpenStruct.new o.instance_delegate.update(:a=>1) o.a.assert == 1 end end method :[] do test do o = OpenStruct.new( { :a => 1 } ) o[:a].assert == 1 end end method :[]= do test do o = OpenStruct.new( { :a => 1 } ) o[:b] = 2 o.b.assert == 2 end end class_method :new do test "old functionality" do o = OpenStruct.new o.foo.assert.nil? o.foo = :bar o.foo.assert ==:bar o.delete_field(:foo) o.foo.assert.nil? o1 = OpenStruct.new(:x => 1, :z => 2) o1.x.assert == 1 o1.z.assert == 2 o2 = OpenStruct.new(:x => 1, :z => 2) o1.assert == o2 end test "via block" do person = OpenStruct.new do |p| p.name = 'John Smith' p.gender = :M p.age = 71 end person.name.assert == 'John Smith' person.gender.assert ==:M person.age.assert == 71 person.address.assert ==nil end test "via hash and block" do person = OpenStruct.new(:gender => :M, :age => 71) do |p| p.name = 'John Smith' end person.name.assert == 'John Smith' person.gender.assert == :M person.age.assert == 71 person.address.assert == nil end test "subclass via block" do person_class = Class.new(OpenStruct) person = person_class.new do |p| p.name = 'John Smith' p.gender = :M p.age = 71 end person.name.assert == 'John Smith' person.gender.assert == :M person.age.assert == 71 person.address.assert == nil end test "subclass via hash and block" do person_class = Class.new(OpenStruct) person = person_class.new(:gender => :M, :age => 71) do |p| p.name = 'John Smith' end person.name.assert == 'John Smith' person.gender.assert == :M person.age.assert == 71 person.address.assert ==nil end end end test_case Hash do method :to_ostruct do a = { :a => 1, :b => 2, :c => 3 } ao = a.to_ostruct ao.a.assert == a[:a] ao.b.assert == a[:b] ao.c.assert == a[:c] end method :to_ostruct_recurse do test do a = { :a => 1, :b => 2, :c => { :x => 4 } } ao = a.to_ostruct_recurse ao.a.assert == a[:a] ao.b.assert == a[:b] ao.c.x.assert == a[:c][:x] end test "with recursion" do a = {} a[:a] = a ao = a.to_ostruct_recurse ao.a.assert == ao end test "advanced usage" do h = { 'a' => { 'b' => 1 } } o = h.to_ostruct_recurse( { h['a'] => h['a'] } ) o.a['b'].assert == 1 Hash.assert === o.a end end end facets-2.9.3/test/standard/test_uri.rb0000644000004100000410000000110011714455227017764 0ustar www-datawww-datacovers 'facets/uri' test_case URI do class_method :hash_to_query do test do h = { :a=>1, :b=>2 } r = URI.hash_to_query(h) assert(r == "a=1;b=2" || r == "b=2;a=1") end end end test_case Object do method :uri do test do "abc%3Fxyz".assert == uri("abc?xyz") end end method :unuri do test do "abc?xyz".assert == unuri("abc%3Fxyz") end end end test_case Hash do method :to_uri do test do h = { :a=>1, :b=>2 } r = h.to_uri assert(r == "a=1;b=2" || r == "b=2;a=1") end end end facets-2.9.3/test/standard/test_equitable.rb0000644000004100000410000000154011714455227021150 0ustar www-datawww-datarequire 'facets/equitable' test_case Equitable do c = Class.new c.class_eval { include Equitable(:a,:b) attr_accessor :a, :b } method :== do test "equatable with arguments" do c1,c2 = c.new,c.new c1.a = 10; c1.b = 20 c2.a = 10; c2.b = 20 assert(c1 == c2) c1.a = 10; c1.b = 10 c2.a = 10; c2.b = 20 refute(c1 == c2) c1.a = 10; c1.b = 20 c2.a = 20; c2.b = 20 refute(c1 == c2) end end =begin def test_equate_on_old c = Class.new c.class_eval { attr_accessor :a, :b ; equate_on :a,:b } c1,c2 = c.new,c.new c1.a = 10; c1.b = 20 c2.a = 10; c2.b = 20 assert_equal( c1, c2 ) c1.a = 10; c1.b = 10 c2.a = 10; c2.b = 20 assert_not_equal( c1, c2 ) c1.a = 10; c1.b = 20 c2.a = 20; c2.b = 20 assert_not_equal( c1, c2 ) end =end end facets-2.9.3/test/standard/test_date.rb0000644000004100000410000000227611714455227020121 0ustar www-datawww-datacovers 'facets/date' test_case Date do setup "Date 2005-05-20" do @d = Date.civil(2005, 04, 20) end method :to_date do test do @d.to_date.assert.instance_of?(::Date) end end method :to_time do test do @d.to_time.assert.instance_of?(::Time) end end method :to_s do test do @d.to_s.assert == "2005-04-20" end end method :stamp do test do @d.stamp.assert == "2005-04-20" end end method :stamp do test do @d.stamp(:short).assert == "20 Apr" end end method :stamp do test do @d.stamp(:long).assert == "April 20, 2005" end end method :days_in_month do test do @d.days_in_month.assert == 30 end end method :days_of_month do test do @d.days_of_month.assert == (1..(@d.days_in_month)).to_a end end end test_case String do method :to_date do test do s = "2005-10-31" d = s.to_date d.day.assert == 31 d.month.assert == 10 d.year.assert == 2005 end end end test_case Time do method :to_date do test do t = Time.now #parse('4/20/2005 15:37') t.to_date.assert.instance_of?(::Date) end end end facets-2.9.3/test/standard/test_thread.rb0000644000004100000410000000070111714455227020442 0ustar www-datawww-datacovers 'facets/thread.rb' test_case Array do method :threaded_map do test do r = [1,2,3].threaded_map{ |e| e + 1 } r.assert == [2,3,4] end end method :threaded_map_send do test do r = [1,2,3].threaded_map_send(:+, 1) r.assert == [2,3,4] end test "with_block" do r = [[1,2,3],[2,3,4],[3,4,5]].threaded_map_send(:select){ |x| x > 2 } r.assert == [[3],[3,4],[3,4,5]] end end end facets-2.9.3/test/standard/test_argvector.rb0000644000004100000410000000246311714455226021175 0ustar www-datawww-datacovers 'facets/argvector' test_case Argvector do method :parameters do test do line = "-x baz --foo=8 bar" cargs = Argvector.new(line) args, keys = cargs.parameters args.assert == ['baz','bar'] keys.assert == {'foo'=>'8','x'=>true} end test "with arity" do line = "-g a -x b -x c" cargs = Argvector.new(line, :g=>1, :x=>1) args, keys = cargs.parameters keys.assert == {'g'=>'a','x'=>['b','c']} args.assert == [] end test "repeated option" do line = "-x baz --foo=1 --foo=2 bar" cargs = Argvector.new(line) args, keys = cargs.parameters args.assert == ['baz','bar'] keys.assert == {'x'=>true,'foo'=>['1','2']} end test do line = "-q baz --aq 5 bar" cargs = Argvector.new(line,'aq'=>1) words, flags = cargs.parameters words.assert == ['baz','bar'] flags.assert == {'q'=>true,'aq'=>'5'} end end method :preoptions do test do line = "-x --foo=7 baz -y bar" cargs = Argvector.new(line) flags = cargs.preoptions flags.assert == {'x'=>true,'foo'=>'7'} end end method :flags do test do line = "-x baz --foo=8 bar" cargs = Argvector.new(line) flags = cargs.flags flags.assert == ['x'] end end end facets-2.9.3/test/standard/test_cloneable.rb0000644000004100000410000000160711714455226021124 0ustar www-datawww-datarequire 'facets/cloneable' test_case Cloneable do foo = Class.new do include Cloneable def initialize @bar=[] end def bar_id @bar.object_id end end method :dup do test do a = foo.new b = a.dup a.bar_id.refute == b.bar_id end test "tainted" do a = foo.new a.taint b = a.dup b.assert.tainted? end test "frozen" do a = foo.new a.freeze b = a.dup b.refute.frozen? end end method :clone do test do a = foo.new b = a.clone assert(a.bar_id != b.bar_id, "should not be equal") end test "tainted" do a = foo.new a.taint b = a.clone assert b.tainted?, "b should be tainted" end test "frozen" do a = foo.new a.freeze b = a.clone assert b.frozen?, "b should be frozen" end end end facets-2.9.3/NOTICE.rdoc0000644000004100000410000001416711714455227014675 0ustar www-datawww-data= COPYRIGHT NOTICES == Ruby Facets Copyright:: (c) 2005,2011 Thomas Sawyer Copyright (c) 2005,2011 Thomas Sawyer You may distribute this software under the same terms as Ruby. == Ruby/Extensions Copyright:: (c) 2004 Gavin Sinclair License:: Ruby Copyright (c) 2004 Gavin Sinclair Ruby/Extensions (extensions.rubyforge.org) is copyrighted free software created and maintained by Gavin Sinclair (gsinclair@soyabean.com.au) and released under the same license as Ruby. THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. == Nitro/Glue Copyright:: (c) 2006, George Moschovitis License:: BSD-3-Clause Copyright (c) 2006, George Moschovitis All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. == ActiveSupport Copyright:: (c) 2005-2011 David Heinemeier Hansson License:: MIT Website:: http://rails.org Copyright (c) 2005-2011 David Heinemeier Hansson 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. == Ruby Treasures Copyright:: (c) 2001 Paul Brannan License:: Ruby License Ruby Treasures 0.1 Copyright (c) 2001 Paul Brannan You may distribute this software under the same terms as Ruby (see the file RUBY.txt that was distributed with this library). == Metaid Copyright:: (c) why the lucky stiff Copyright (c) why the lucky stiff == CLAP Copyright:: (c) 2010 Michel Martens License:: MIT Website:: https://github.com/soveran/clap Copyright (c) 2010 Michel Martens 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. == String#natcmp Copyright:: (c) 2003 by Alan Davies License:: Custom String#natcmp is based on Martin Pool's "Natural Order String Comparison" originally written in C. (see http://sourcefrog.net/projects/natsort/) This implementation is Copyright (C) 2003 by Alan Davies This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. facets-2.9.3/README.rdoc0000644000004100000410000001714211714455227014645 0ustar www-datawww-data= Ruby Facets "ALL YOUR BASE ARE BELONG TO RUBY" == Introduction Ruby Facets is the premiere collection of general purpose method extensions and standard additions for the Ruby programming language. Facets houses the largest single collection of methods available for extending the core capabilities of Ruby's built-in classes and modules. This collection of extension methods are unique by virtue of their atomicity. The methods are stored in individual files so that each can be required independently. This gives developers the potential for much finer control over which extra methods to bring into their code. In addition Facets provides a collection of extensions to Ruby standard library plus a small collection of add-on classes and modules. Together these libraries constitute an reliable source of reusable components, suitable to a wide variety of usecases. == Resources * Homepage: http://rubyworks.github.com/facets * Report Bugs: http://github.com/rubyworks/facets/issues * Mailing List: http://groups.google.com/group/facets-universal/topics * Wiki Pages: http://wiki.github.com/rubyworks/facets * Source Code: http://github.com/rubyworks/facets == Documentation Facets has special documentation needs due to it's extensive bredth. The documentation generated when installing via RubyGems, or the YARD docs provided by rubydoc.info can be somewhat unweildly because it combines all of Facets in one large set. When using these resources, it is important to remain aware of the source location of particular methods. For better organized online documentation, generated to separate core extensions from standard libraries, see the {Learn Facets}[http://rubyworks.github.com/facets/learn.html] page on the website for links to available documentation. == Installation === RubyGems The easiest way to install is via RubyGems. $ gem install facets === Setup.rb Facets can be installed the old-fashioned way using Ruby Setup (http://rubyworks.github.com/setup). Download and unpack the .tar.gz package and run setup.rb, like so: $ tar -xvzf facets-2.x.x.tar.gz $ cd facets-2.x.x $ sudo setup.rb Facets 2.8+ requires Ruby 1.8.7 or higher. == Mission Facets holds to the notion that the more we can *reasonably* integrate into a common foundation, directed toward general needs, the better that foundation will be able to serve the community. There are a number of advantages here: * Better Code-reuse * Collaborative Improvements * Greater Name Consistency * One-stop Shop and Installation == Usage === CORE Library At the heart of Ruby Facets is the CORE extensions library. CORE provides a sizable collection of generally useful methods, along with a few supporting classes, that extend the functionality of Ruby's core classes and modules. With the exception of a few *uncommon* extensions, CORE contains anything that will load automatically when issuing: require 'facets' This loads all the CORE functionality at once. If you plan to use more then a handful of Facets core methods it is recommended that you require the library in this way. However, you can also "cherry pick" the CORE library as you prefer. And for uncommon extensions this must be done. The general require statement for a core extension library is: require 'facets//' For example: require 'facets/time/stamp' Most "atoms" contain only one method, but exceptions occur when methods are closely tied together. You can load per-class or per-module groups of core methods by requiring the class or module by name. For example" require 'facets/time' Will require all the core Time method extensions. Note that some methods that were part of CORE in 1.8 and earlier are now part of MORE libraries. A good example is 'random.rb'. There were separated because they had more specialized use cases, where as CORE extensions are intended as general purpose. ==== Method File Names Operator method redirect files are stored using English names. For instance `Proc#*` is `proc/op_mul`. For reference, here is the chart. +@ => op_plus -@ => op_minus + => op_add - => op_sub ** => op_pow * => op_mul / => op_div % => op_mod ~ => op_tilde <=> => op_cmp << => op_lshift >> => op_rshift < => op_lt > => op_gt === => op_case == => op_equal =~ => op_apply <= => op_lt_eq >= => op_gt_eq | => op_or & => op_and ^ => op_xor []= => op_store [] => op_fetch Facets simply takes the '*' and translates it into a string acceptable to all file systems. Also, if a method ends in '=', '?' or '!' it is simply removed. === MORE Library (aka Standard Library) On top of the extensive CORE library, Facets provides extensions for Ruby's standard library, as well as very small collection of additional modules and classes to supplement it. Use this library like you would any other 3rd party library. The only difference between Facet's Standard library and other libraries is the lack of any enclosing @Facets::@ namespace. This is becuase the libraries provided by Facets are fairly low-level and very general purpose. When using Facets extended versions of Ruby's standard libraries, the libraries have to loaded manually, of course. However you do not need to load Ruby's library first, as the Facets' library will do that automatically. For example, normally one load Ruby's OpenStruct class via: require 'ostruct' To load 'ostruct.rb' plus Facets extensions for it simply use: require 'facets/ostruct' For details pertaining to the functionality of each feature, please see the API documentation. == Contribute This project thrives on contribution! If you have any extension methods, classes or modules that you think have very general applicability and would like to see them included in this project, don't hesitiate to submit. Also, if you have better versions of any thing already included or simply have a patch, they are more than welcome. We want Ruby Facets to be of the highest quality. == Authors This collection was put together by, and largely written by Trans. He can be reached via email at transfire at gmail.com. Some parts of this collection were written and/or inspired by other persons. Fortunately nearly all were copyrighted under the same open license, the Ruby License, or the more liberal BSD and MIT licenses. In the one or two exceptions I have included the copyright notice with the source code. Any code file not specifically labeled othewise shall fall under the Ruby License. In all cases, I have made every effort to give credit where credit is due. You will find these acknowledgments embedded in the source code. You can see them in "CREDIT:" and/or "@author" lines. Also see the {Contibutors page}[https://github.com/rubyworks/facets/wiki/Contributors] on the Wiki for a list of all contributing Rubyists. If anyone is missing from the list, please let me know and I will correct right away. Thanks. == License The collection PER COLLECTION is licensed as follows: Ruby Facets Copyright (c) 2004,2010 Rubyworks Distributed under the terms of the Ruby license. The Ruby license is a dual license that also provides for use of the GPL. Complete texts of both licenses accompany this document (see LICENSE). Acknowledgments and Copyrights for particular snippets of borrowed code are given in their respective source. All licenses are either compatible with the Ruby license or the original author has given permission for inclusion of their code under such license. "ALL YOUR BASE ARE BELONG TO RUBY!" Ruby Facets, Copyright (c)2005,2011 Rubyworks Do you Ruby? (http://ruby-lang.org) facets-2.9.3/HISTORY.rdoc0000644000004100000410000026547711714455227015071 0ustar www-datawww-data= Facets Release History == 2.9.3 / 2011-12-31 Happy New Year! Ruby Facets kicks off the year with a 2.9.x release. This release adds a number of new methods, a few general improvements and bug fixes, a couple of deprecations and finally settles the project down to a two-part core/standard project organization. Changes: * New Features * Add Hash#url_params. (Matt Kirk) * Add Enumerable#hashify. (Ronen Barzel) * Add String#briefcase, similar to #titlecase. * Add Kernel#hierarchical_send (better replacement for preinitialize.rb). * Add Class#hierarchically, which supports #hierarchical_send. * Add Array#median, to get the sorted middle of an array. * Add Math#percentile and Math#median. * Add Instantiable mixin (returns from Mixers spin-off project). * Add Equitable mixin (returns from Mixers spin-off project). * Add Cloneable mixin (returns from Mixers spin-off project). * Add Array#each_pair and #each_value. * Add Numeric#positive? and #numeric?. * Add Method#* and #^ composition methods. (Mike Burns) * Add back Fixnum::MAX and MIN constants. * Add Binding#with. * Improved Features * Improve FileUtils#amass to be more robust. * Improve String#snakecase to convert spaces to underscores. * Improve String#camelcase to convert spaces to "camels". * Improve String#snakecase to not handle path names (use #pathize). * Improve String#camelcase to not handle module names (ise #modulize). * Improve Numeric#approx? bu using ratio. * Renamed Features * Rename Enumerable#has? to #incase?. * Bug Fixes * Fix Hash#rekey to keep default_proc. * Fix Binding#self to not be defined for Rubinius. * Deprecations * Deprecate Preinitializable mixin. * Deprecate main.rb, spun-off to `main_like_module` gem. * Implementation Details * Reconsolidated library into just two parts, `core` and `standard`. * The term "more" is just a synonym for "standard" now. * Relative requires are being used more extensively. * Collection scripts, e.g. `require 'facets'`, are static. == 2.9.2 / 2011-08-23 The main purpose of this release is a fix for Module#redefine_method, so it will not conflict with ActiveSupport. Beyond that a handful of new methods have been added. This release also marks the start of using a src/ directory to generate the lib/ directory. Changes: * New Features * Add Enumerable#map_with and alias #zip_map. * Hash#delete_values returns removed keys (#12). * Add clap-like command-line parser to Shellwords. * Add Module#let, akin to RSpec's method. * Add uncommon Module#method_clash method. * Add uncommon Class#singleton? method. * Bug Fixes * Fix Module#redefine_method to use #remove_method. * Fix Kernel#object_hexid, or at least try to do so again. * Fix Exception#detail to not return backtrace if nil. == 2.9.1 / 2011-01-30 Primarily this release fixes a couple of small issues. But also a handful of new methods have been added. Changes: * New Features: * Add FileTest#absolute? and #relative? * Add FileTest#contains? * Add FileTest#safe? * Add FileUtils#amass * Add FileUtils#outofdate * Add FileUtils#stage * Add Kernel#yes? and Kernel#no? * Add Enumerable#has? (TOUR library) * Add Digest#salted_digest, etc. * Add Digest#base64digest (1.9.2 method) * Add String#random_binary * Improved Features * Better OS detection in Platform class and RBConfig module * Moved CPU byte order methods from RBConfig to Platform class * General improvements to Platform class API * Bug Fixes * Module#redefine_method need not check pre-existence of method * Fix string/unquote.rb recursive require * Kernel#object_hexid varies on CPU arch, not Ruby version. == 2.9.0 / 2010-09-01 This release is fairly extensive as it was originally intended to be v3.0. After further consideration it was decided to reserve v3.0 for the polish of real world feedback and more progressive changes. The primary focus of this release has been the completion of migrating Facets into a true extensions library. With this release almost all add-on classes and mixins have now been spun-off to other projects. Only the most general purposes add-on classes and mixins remain. A new TOUR library division has also been added to complement CORE and MORE. This division houses purely optional extensions. The new division serves a couple of useful purposes. In particular, it helps separates the standard library extensions from optional core extension in the RDocs and thus makes the perfect place to vet new extension ideas. One important change that will effect anyone using Facets along side ActiveSupport is that Facets no longer tries to conditionally avoid method overlaps with ActiveSupport. This is fine for the upcoming ActiveSupport 3.0 library which extends core classes directly instead of using mixins. One need only require 'facets' in the Rails config/preinitializer.rb file and ActiveSupport will take precedence over Facets. For older versions of ActiveSupport, the best approach is to cherry pick from Facets just the extensions you want, thus avoiding any conflicts. There are actually only a dozen or so overlaps and all are intended to compatible, but it doesn't hurt to be sure. Lastly, it is worth mentioning that this release has been more thuroughly tested than any version of Facets to date. Thanks to RVM this release runs green on Ruby 1.8.6, 1.8.7 and 1.9.2. Changes: * New Features * Add Kernel#temporarily, set variables temporarily and eval block * Add Kernel#deep_clone, a better alternative to #deep_copy * Add Kernel#present? and Kernel#presence * Add Kernel#not and #not? * Add Array#extract_options!, for pulling options off argument list * Add Regexp#|, operator for Regexp#union * Add Array#percentile and Array#median * Add Module#memo, for instance level memoization * Add YAML.read method * Add Pathname#include? * Add Module#anonymous? * Add Module#copy_inheritor * Add Indexable#from and Indexable#upto * Add Array#from and Array#thru * Add NA class via na.rb * Add Memoizable in memoizable.rb for a more robust memoization system * Add Module#safe_memo in thread.rb for thread safe memoization * Add Kernel#sandbox in thread.rb for threaded $SAFE=4 evaluation * Add Hash#subset * Add Kernel#Y to tour library * Add numerous Math extensions * Deprecations * Deprecate Module#attr_toggler as a YAGNI * Deprecate Kernel#class_eval b/c of it's confusing behavior * Deprecate Module#once is no longer an alias for #memoize * Deprecate Integer#succ(n) (for compatibility reasons) * Deprecate Stackable, it's method were moved to CORE * Deprecate Kernel#populate and #set_from (use #assign and #assign_from) * Deprecate Kernel#non_nil? since #not_nil? is enough * Deprecate #__HERE__ b/c implementation was unreliable * Deprecate Time#since, use #less instead * Deprecate Time#advance, use #shift instead * Deprecate Kernel#super_as (no good way to get callers method name) * Deprecate Integer#clear_bit, use #bit_clear instead * Deprecate Kernel#resc, use String#to_re or #to_rx instead * Deprecate Module#modspace * Deprecate Kernel#__ and class X for Proc#partial, use NA instead * Deprecate autoreload.rb has been spun-off to a separate project * Deprecate Module#nesting, b/c redundant and overlap with Module.nesting * Renamed Features * Rename Module#parent to Module#enclosure * Rename Module#parents to Module#enclosures * Rename Module#parent_name to Module#modname * Rename Array#recurisvely to Array#recurse * Rename Hash#recurisvely to Hash#recurse * Rename Enumerable#recursive to Enumerable#recursively * Rename Array#recursive to Array#recursively * Rename Hash#recursive to Hash#recursively * Rename Kernel#silence_warnings to Kernel#disable_warnings * Rename Hash#recursive_merge to Hash#deep_merge * Rename Class#prepend to Class#preallocate * Rename File#atomic_write to FileUtils#atomic_write * Rename Module#conflict to Module#method_clash * Rename Class#inheritor to Module#class_inheritor * Rename Symbol#re_s to Symbol#as_s * Rename String#chars to String#characters * Rename String#outdent to String#unindent * Rename Time#round to Time#round_to * Rename Time#hence to Time#shift (but keep aliases) * Rename Hash#zipnew to Hash#zip * Moved Libraries * Move roman.rb to integer/roman and string/roman.rb * Move blank.rb to kernel/blank.rb * Move facets-live.rb to facets/auto_core.rb * Move cattr.rb to MORE library * Move duplicable.rb to kernel/dup.rb * Move bitmask.rb to integer/bitmask.rb * Move enumerable/divide.rb to array/divide.rb * Move enumerable/split.rb to array/split.rb * Move enumerable/entropy.rb to array/entropy.rb * Move enumerable/probability.rb to array/probability.rb * Move enumerable/duplicates.rb array/duplicates.rb * Move module/enclosure.rb to optional TOUR libs * Move kernel/instance_exec to option TOUR libs * Bug Fixes * Fix Fixed Hash#rekey! from clobbering previous keys * Fix Exception#raised? is a class method * Fix Enumerator#fx should use #map instead of #each * Fix String#splice needs String#store * Fix Kernel#blank? empty condition was faulty * Fix Comparable#bound needs clip.rb, not cap.rb * Fix String#file needs to pass block * Fix String#edit_distance use new encodings for Ruby 1.9 * Improved Features * New lib/tour division of libraries * Module#class_extend dynamically creates append_features method * Kernel#require_all is only for relative requires * __DIR__ can take subdirectory arguments * Hash#join has more sensible default separator (' ') * Some OpEsc escapes have been renamed * Kernel#assign does not accept a block * Kernel#try is now like ActiveSupport's * Improved #respond (which is like old #try) * Remove all `if defined?(ActiveSupport)` conditions * Use #random_range to support specialized Range#at_rand functionality * Use Comparable.[] instead of Comparable() * Array#rotate rotates in opposite direction than before (b/c or Ruby 1.9) == 2.8.4 / 2010-04-27 A minor point release just to get a few improvements out there before endeavering into more extensive work for the next major release. * New Features * Added #glob_relative to Pathname * Deprecations * Deprecated BlankSlate (use BasicObject) * Deprecate hashbuilder.rb * Removed casting_hash.rb, moved to new library * Removed opencollection.rb, moved to new library * Removed ansicode.rb, use ansi gem * Bug Fixes * changed Numeric#length to return self, not to_s.self * Fix mispelling of Class#descendants * Other Improvements * Range#at_rand has been optimized * Kernel#singleton_class no longer can take a block * Hash#to_proc takes response argument replacing #to_proc_with_response * OpenHash becomes more like OpenObject and OpenObject becomes bare bones * Range#at_rand optimized for Fixnum/Bignum instead of Integer == 2.8.3 / 2010-04-10 New release which makes a few adjustments in Kernel core extensions, adds a few new extensions and additions, plus other small improvements. The biggest change is the addition of Recusor, which is created via Enumerable#recursive. This class is somewhat like Enumerator and provides a number of recursive methods. Changes: * 9 New Core Extensions * Enumerable#recursive provides a number of other recursive methods. * Enumerable#visit can be used to recursively iterate any Enumerable. * Module#set has been added (from Sinatra). * Symbol#/ is added to be like String#/. * Struct#to_h is added and will ultimately replace Struct#attributes. * ObjectSpace#reflect routes method calls to Kernel context. * Hash#to_module converts a hash to mixin module (Jay Fields). * Kernel#dup! is same as #try_dup from extlib. * Add File#ext which is a useful variation of #extname (Lavir the Whiolet). * 3 Core Extensions Renamed * Renamed #set_from to #assign_from (alias remains until Kernel#set is considerd). * Renamed #populate to #assign and improve. * Kernel#instance_vars is now Kernel#instance and also more useful. * 1 Core Deprecation * Removed #instance_eval hack. * 2 Core Bug Fixes * #map_with_index now uses #each_with_index. * #to_proc_with_response spelling correction. * 1 Core Adjustment * Aliased #metadef to #meta_def. * 3 New More Libraries * casting_hash.rb provides CastingHash class, a hash with flexible keys and values. * prepend.rb allows for AOP-like inclusion of modules. * roman.rb provides simple roman numeral extensions to String and Integer. * 5 More Improvements * Pathname#visit for iterating all entries beneath a path (chikamichi). * Pathname#to_str, b/c Pathname is basically a type of String (from extlib). * Range#at_rand in random.rb handles Float ranges (Lavir the Whiolet). * FileUtils#cp_rx provides controlled copies. * Stash class in stash.rb is improved and is now available as a stand-alone library. * ioredirect.rb has been removed as IORedirect no longer worked. * plugin_manager.rb has been removed. Use 'plugin' gem instead. == 2.8.2 / 2010-02-22 This release fixes a bug by removing Numeric#size. Turns out that was a core method already. It includes an "auditing" of the core enumerable method which has led to a few modifications most noteable amoung them renaming #map_detect to #find_yield and #compact_map to #purge. Changes: * 7 New Core Extensions * Add Enumerable#each_with_object. * Add #collapse which is a shortcut for flatten.compact. * Add Numeric#spacing (Mr. Groff) * Add Array#uniq_by! to complement Enumerable#uniq_by. * Add String#exclude? as opposite of #include? * Add Enumerable#exclude? as opposite of #include? * Add Proc#bind_to * 2 Extensions Renamed * Rename Enumerable#compact_map to #purge. * Rename Enumerable#map_detect to #find_yield. * 4 Deprecations * Deprecate #inject!/#injecting in favor of #filter. * Deprecate Array#** as alias of #product. * Remove Numeric#size, as it was already used by core. * Spun tracepoint.rb off as a seprate library. * 3 Other Changes * Integer#multiple? handles zero as an argument. * facets.rb is now dynamically loaded instead of code generated. * General imporvements to date.rb. == 2.8.1 / 2009-12-25 This release simply fixes a few minor issues. Changes: * 1 New Standard Extension * Added Pathname#glob_relative to pathanme.rb. * 3 Adjustments * Loading string/tab.rb no longer loads margin.rb or expand_tab.rb. * Fixed FileList method delegations. * Numeric#length and #size return +self+, not +to_s.length+. == 2.8.0 / 2009-11-05 Facets 2.8 effectively completes the MORE library clean-up which peaked with the previous 2.7 release. Another eight libraries have been deprecated, a few of them spun-off to a separate project. However, this verison also reverts a few of the deprecations made in the last version. These libs will remain in Facets's MORE library for the forseeable future. This version effectively concludes the MORE library clean-up. The next, and last version before Facets 3.0, will focus on "auditing" the CORE library. Changes: * 6 Libraries "Undeprecated": * ini.rb * linkedlist.rb * matcher.rb * memoizer.rb * roman.rb * semaphore.rb * 5 Libraries Deprecated: * fileable.rb (too esoteric) * ioredirect.rb (needs better implementation) * coroutine.rb (because of Fiber) * capsule.rb (may be spun-off) * recorder.rb (may be spun-off) * 3 Libraries Spun-Off and Deprecated: * ansicode.rb ansi * progressbar.rb ansi * logger.rb ansi * Additonal Enhancements: * Kernel#extend can now take a block * Fixed kernel#d so it is useable * Added Range#at_rand (thanks to Tyler Rick) * Added Enumerable#map_detect (thanks to Scott Taylor) * String#/ calls File.join * Added String#newlines and String#cleanlines * String#titlecase includes apostrophe in words * BasicObject/BlankSlate is more compliant with 1.9.1 design * Enumerable#count can take multiple items, treats as logical Or * Class#class_extend extends class level, not class_eval * Integer#succ(n) becomes Fixnum#succ(n), succ.rb * Complete rewrite of Inheritor * Shellwords extensions have been reworked * Added String#similarity * Added Levenshtein String#edit_distance method * And other minor improvements (some thanks to ccjr) == 2.7.0 / 2009-08-01 Facets 2.7 is the biggest release of Facets since 2.4. Rather then trickle-release these changes over the course of the 2.6.x series, I made the decision to let 2.7 have them all at once. In so doing this release nearly completes the process of trimming down the MORE library to its essentials. Over 40 high-level libraries have been spun-off as separate gems and/or deprecated. No doubt this is a big change for Facets, and the transition may be a bit bumpy over the short-term, but I am certain that in the long-run everyone involved will be better served. To help, I have listed the effected libraries and the alternate gems availble to take their place. A few other changes have also been made in the release that may also effect your code. In particular you should note that #class_extension has been renamed to #class_extend (require 'facets/class_extend'). In addition we have added a few new core methods such as Exception#raised? and Symbol#thrown?. Changes: * Spun-Off Projects These libraries have been deprectated from Facets entirely, but are available as separate gems (or soon will be). LIBRARY GEM -------------------- ------------------------------ overload.rb overload binreadable.rb binaryio downloader.rb downloader xoxo.rb xoxo bicrypt.rb bicrypt typecast.rb typecast association.rb association syncarray.rb sync synchash.rb sync paramix.rb paramix crypt.rb crypt3 lrucache.rb lrucache net/smtp_tls.rb smtp_tls advisable.rb advisable buildable.rb buildable memoizer.rb memoizer harray.rb sparray sparse_array.rb sparray iteration.rb iteration interval.rb stick infinity.rb stick pool.rb pool linkedlist.rb linkedlist semaphore.rb semaphore pqueue.rb pqueue censor.rb language matcher.rb language basex.rb radix minitar.rb archive-tar-minitar -or- folio * Spun-Off But Still Available These libraries have been spun-off into stand-alone gems, but remain available via Facets too. Ultimately some of these will be removed from Facets too (in particular the ansi libraries). LIBRARY GEM -------------------- ------------------------------ ansicode.rb ansi progressbar.rb ansi logger.rb ansi tracepoint.rb tracepoint dictionary.rb dictionary recorder.rb recorder ostructable.rb ostructable -or- openhash openobject.rb openhash opencollection.rb openhash opencascade.rb openhash openhash.rb openhash openmodule.rb openmodule fileable.rb fileable enumerablepass.rb enumargs * Deprecations Without Current Replacement The libraries have been deprecated but do not yet have replacements. Seperate gems for these are planned though. * bbcode.rb * ini.rb * settings.rb * xmlhash.rb * Deprecations Merged Into CORE These libraries have been deprecated because their functionality was merged into the CORE library and/or made available in some another way. * 1stclassmethod.rb #method! and #instance_method! are now part of CORE. * elementor.rb #per has been added to CORE. * elementwise.rb #ewise has been added to CORE. * consoleutils.rb #ask is in CORE, for the rest see Ansi or Clio project. * attr.rb Added Module#attr_setter to CORE, and separated the rest in MORE. * General Deprecations These libraries have simply been deprecated because they were found lacking in some significant fashion. * nilstatus.rb Poved rather useless, not to mention trivial. * heap.rb Heap was just an alias for PQueue anyway. Use 'pqueue' instead. * dependency.rb Other solutions exist that are much better (like Advisable). * classmethods.rb #class_extend solution is more robust. * ziputils.rb Have a look at Folio (gem install folio) for replacement. * unheritable.rb Implementation is trivial and usefulness questionable. * instantise.rb Replaced by instance_function.rb. * Other Enhancements * Fixed Proc#curry to work with #define_method (Thanks to R.Potter) * Module#class_extension has been renamed to #class_extend (require 'facets/class_extend'). * kernel#instance is no longer in core; now it is an extra monkey patch for #instance_eval. * Kernel#this has been removed. It is equivalent to 'method(__method__)'. * BlankSlate is now an alias for BasicObject, and will be deprecated in the future. * Kernel#method! and Module#instance_method! now use a global variable for their cache. * #object_state (old name was #state) has been added to core. == 2.6.0 / 2009-07-03 Facets 2.6.0 removes htmlfilter.rb and cssfilter.rb due to licensing incompatability. These scripts are now available as a separate package called 'htmlfilter'. Also removed are a few MORE libs that were too expiremental and/or not robust enough. Effectively this finishes up the "spring cleaning" of the MORE lib mentioned a few releases back. But it also marks a new start in trimming MORE down further. We have decided to do this for three reasons 1) Some of the MORE libs would be better served as separate projects. 2) Facets will become a tighter library, primarily focused on extensions. And 3) all libraries involved will become easier to maintain and thus more robust in the long run. This release also fixes an important arity bug with the recently added Module#extend method --one of the very few actual core overrides in Facets. Changes: * 7 Major Enhancements * Removed htmlfilter.rb due to licensing issues. * Also removed cssfilter.rb ('gem install htmlfilter' now) * Removed rwdelegator.rb, simply not a robust solution. * Removed buildable.rb, api is too confusing. * Removed meta.rb which was not very useful and too expiremental anyway. * Removed prototype.rb, which needs it's own project. * 3 Minor Enhancements * Removed Kernel#__HERE__ as it simply cannot work. (Ruby 1.9.2 will offer #source_location for the same, btw) * Returned binding/opvars to core. * Added Integer#length as suggested by Victor H. Goff III. * 1 Bug Fix * Fixed arity issue with Module#extend. == 2.5.2 / 2009-04-07 Facets 2.5.2 is a simple maintentance release which fixed a few issues in the new to_hash.rb library. This release also added String#lowercase and String#uppercae. Changes: * 1 Major Enhancement * added string/uppercase and lowercase * 1 Minor Enhancement * adjustments to to_hash.rb == 2.5.1 / 2009-03-05 Facets 2.5.1 fixes a few bugs, makes some small but nice additions and improves 1.9 compatibility. The most important addition to make note of is Object#extend, which has been overridden to allow a block parameter. This is one of only two or three actual "monkey patches" in all of Facets. The block, when provided, is used to create an annonymous module which then extends the reciever. This is a "good practice" way to extend objects, rather than using class_eval on the singleton class. Special thanks to Erik Veenstra, Pit Capitan and especially Sandor Szücs for their contributions to this release. Changes: * 7 Major Enhancements * added Hash#group_by_value (thanks to Erik Veenstra) * added String#file * added Hash#new_with (Pit Capitan) * added module/extend.rb, now can take a block. * added hook.rb * added to_h_auto * overhauled to_hash.rb, now has multiple methods * 10 Bug Fixes * corrected ostruct.rb to test for frozen state on updates * fixed String#left_align * fixed conflict between test_name.rb and test_arguments.rb * fixed Enumreable#split when reciever is empty array * fixed coruption of reciever by Hash#collate (thanks to Tilo Sloboda) * fixed Array#to_h, h={} was not initialized * fixed test of Module#conflict according ruby19 * fixed Hash#dearray_singluar_values * association.rb stores reference when using #new * changed Array#product to make it compatible to ruby 19, deleted block parameter * 5 Minor Enhancements * split enumerable/collect into map_with_index and compact_map * improved Array#to_h for 1.9 using flatten(1) * Dictionary#replace can take regular Hash too * move test_to_hash.rb from more to core * Doc'd that UnboundMethod#name returns Symbol in 1.9, but String in 1.8 == 2.5.0 / 2008-11-23 Facets 2.5.0 is an important milestone in the development of Facets. This release has been tested against Rails' ActiveSupport library. As long as Facets is loaded after ActiveSupport, everything should work fine. Of course, there's no counting for real world trials, but all ActiveSupport testcases pass under this scenario. Secondly, this release is the first of two (or three) down-scaling releases intended to remove all the remaining "excess" from the library. This is being done for a variety of reasons. Some scripts are substantial enough to be one their own and have been spun-off into separate largely compatible projects. In this release: If you were using... Use this project instead... annotations.rb Anise bytes.rb RichUnits times.rb command.rb Clio consoleutils.rb A few others scripts have been deprecated, without an alternative recourse, simply because they were too weak, such as uploadutils.rb, or highly experimental, such as chain.rb and eventhook.rb. Although this release constitutes an over all slimming down of Facets, two excellent new libraries have been added. 1) *ini.rb* by Jeena Paradies. While YAML is frequently used by Rubyists for configuration files, a full-on serializer like YAML is often overkill. INI files provide a lightweight solution specifically geared for configuration. 2) *filter.rb* by Brian Candler offers lazy evaluation chains of Enumerable methods. This is an elegant way to optimize contiguous maps, selections, etc. --effective even on infinite enumerators. (Note, the name of this library may be changed in the next release.) While work remains to be done, I am happy to say, Facets is finally beginning to approach the level of solidity I set out to achieve just over a year ago. Thank the Maker! Special thanks to Brian Candler, Jeena Paradies and Tyler Rick. Changes: * 9 Major Changes * added Brian Candler's Enumerator::Filter * added sparse_array.rb (was old harray.rb) * added Jeena Paradies' ini.rb * renamed CacheDelegator to Memoizer * renamed DictionaryMatcher to just Matcher * deprecated bytes.rb and times.rb (use RichUnits instead) * deprecated uploadutils.rb; ziputils.rb will be (use Folio) * deprecated annotations.rb (use Anise instead) * deprecated command.rb and consoleutils.rb (use Clio instead) * 5 Minor Changes * deprecated chain.rb (very expiremental) * deprecated eventhook.rb (moved to ToadCode project) * deprecated tagiter.rb (moved to ToadCode project) * moved Hash#symolize_keys and #stringify_keys to core lib (still recommend #rekey instead though) * switched to git as of 2.4.5 * 4 Bug Fixes * memoize.rb, cache was at class-level, now at instance-level * binding/caller.rb, fixed require for callstack.rb * fixed missing require in string/tabto.rb * Fixed some bugs with Time#ago/Time#hence not changing years correctly when you changed months. (For example, Time.utc(2008, 1, 1).ago(12, :months) incorrectly returned 2009-01-01 instead of 2007-01-01.) Changed Time#ago/Time#hence to still work if passed negative number. == 2.4.5 / 2008-10-02 Facets 2.4.5 is a maintaince release. This release is notable however in that it will likely be the last that to use SVN. Facets will be switching to Git. Also, some libraries that have been flagged "to be deprecated" for some time will finally be so. Changes: * 8 Major Enhancements * Re-added date.rb to lore library, and removed from core. (#r1014) * Much improved date.rb extension now in Lore library. (#r1027) * Deprecated kernel/suppress. Use Exception.suppress from now on. (#r1040) * Deprecated string/style.rb. Use English project instead. (#r1074) * Console namespace is no longer supported (for Ansicode). (#r1077) * enumerable/mode.rb, Enumerable#mode returns array since there can be more than one. (#r1079) * OpenCascade automatically creates nodes, use foo? to query. (#r1056) * Change #index_of to #index which now takes a block. * 14 Minor Enhancements * OpenStruct.new can now take a default block, like Hash.new. * Moved variablize methods out of metaid.rb and into separate files (string/ and symbol/). (#r1042) * Added Time#advance. (#r1046) * Speed up of Integer odd/even methods. (#r1057) * Array#index now takes a block (this is a core override). (#r1059) * Spilt file/write.rb into separate method files (append, create, writelines). (#r1073) * Modified Enumerable#split to behave like String#split. (#r1076) * hash/op.rb, split into separate method files. (#r1081) * Added string/modulize. string/methodize handles path names now too. (#r1085) * Class#cattr is now part of core. (#r1089) * Modified Enumerable#split to behave like String#split. [minor] * Removed Rope class. If anything this will have a separate project. * Added doc/news.html and doc/authors.html to website (temporarily?). * Added zlib.rb to Lore library. * 7 Bug Fixes * OpenStruct#to_h dups internal table. (#r1015) * Fixed require of string/xor in bicrypt.rb. (#r1039) * integer/odd.rb, fixed Ruby 1.9 condition. (#r1080) * class/cattr_*.rb fix require bug * opencascade.rb, fixed bug when accessing sub-hash. * typecast.rb, fixed require for string/methodize. * Fixed Pathname#glob to ensure use of ::File. == 2.4.4 / 2008-09-01 Facets 2.4.4 includes a major bug fix that caused Facets not to load properly, having to do with a Time extension. The problem has been fixed. In addition, this release put Facets only a few pending adjustments away from full Rails/ActiveSupport compatibility. Changes: * 10 Major Enhancements * Added string/mask providing powerful string manipulation. (#997) * BasicObject is now just a synonm for BlankSlate unless Ruby 1.9. (#1000) * Added Symbol#plain?, Symbol#query? and Symbol#setter? (#1011) * Removed Time#to_date. * Due to clobberd RI Docs (!) this should have been in Lore lib date.rb * Moved to Lore date.rb. (#1012) * Re-added date.rb to lore library, and removed from core. (#1014) * Much improved date.rb extension now in Lore library. (#1027) * Deprecated kernel/suppress. Use Exception.suppress from now on. (#1040) * Improved date.rb and moved to LORE library, and removed from CORE. [major] * Deprecated kernel/suppress. Use Exception.suppress from now on. [major] * Deprecated String#to_time. * This method reqiures the loading of a number of other standard libs. * We can reconsider adding it again if we decide these other libs should be core. * Or if we find a more suitable way to define the method. * 17 Minor Enhancements * Moved style.rb to string/stylize.rb (#998) * Renamed string/subtract to string/op_sub. Old name will remain for time being for compatability. (#1002) * Module#instance_method_define? now only applies to public methods. (#1003) * Array#index accepts a block (one of the few core overrides). (#1004) * Moved Hash#<< from hash/update.rb to hash/op_push.rb (#1005) * Add facets class files (eg. facets/string) have been made dynamic. (#1013) * Moved variablize methods out of metaid.rb and into separate files (string/ and symbol/). (#1042) * Added Time#advance. (#1046) * Added qua_class.rb. Yea. It really is my favorite. * Added simple functional test that loads all of Facets. * Added a benchmark for measuring how fast Facets loads. (Core < 1sec!) * Made Module#alias_method_chain a public method (for better Rails support). * Wrapped Nilclass#to_f in 1.9 condition. * float/round.rb redirects to numeric/round.rb. * numeric/float.rb holds rounding methods for all classed Numeric, Integer and Float. * Replaced Kernel#instance_exec with Mauricio's version. * Improved String#each_char to work like Ruby 1.9. * This loads strscan.rb. * It is wrapped in a 1.9 condition. * 8 Bug Fixes * Hash#<< now returns self (#1001) * OpenStruct#to_h dups internal table. (#1015) * Fixed require of string/xor in bicrypt.rb. (#1039) * Fixed facets.rb to use relative paths. * Fixed cgi.rb (CGI is a class not a module). * OpenStruct#to_h dups internal table. [bug] * Fixed require of string/xor in bicrypt.rb. [bug] * date.rb (stamp) fixed ref to constant FORMAT. == 2.4.3 / 2008-08-14 Facets is almost fully interoperable with ActiveSupport and Ruby 1.9. We will continue to improve this interoperability in upcoming releases. As a REMINDER, Facets 2.4+ now encourages: require 'facets' This is better than cherry-picking methods. It may seem counter-intuitive, but it actually proves more advantages to do this for the sake of improved interoperability. The practice of cherry-picking can become problematic if other dependent libraries have cherry-picked different methods. In those cases these distinctions go unaccounted and untested. Note that this release does not include a setup.rb script. We are working on a new version of this script, which we plan to include in the next release. This release give special thanks to the following people for their contributions: Ken Bloom, Nick Caruso, Evgeniy Dolzhenko, Andy Freeman, Tomasz Muras and Dave Myron. And of course, to anyone else I failed to mention that has contributed. (NOTE: 2.4.3's changes may actually be long to 2.4.2. Notice the releases are only two days apart. There was an issue with 2.4.2 and it had to be replaced immediately. So take the distinct with a grain of salt.) Changes: * Additions * Add Time#trunc and Time#round to Core. * Add Array#recursively and fixed bug in Hash#recursively. * Add Kernel#instance method which provides a fluent interface to private object space. * Add Symbol#plain?, Symbol#query? and Symbol#setter? * Add Hash#symbolize_keys and #stringify_keys. * Add File#split_root. * Add #glob and #glob_first as extensions to Pathname. * Add NilClass#ergo whic points back to kernel/ergo. * Add #bump method to VersionNumber class. * Add String#mask providing powerful string manipulation. * Add Ken Bloom's DictionaryMatcher class (will be renamed in future version) * Deprecations * Deprecate Hash#keys_to_s and Hash#keys_to_sym. * These are the original versions of these methods. * But now we can use #rekey(:to_s) and #rekey(:to_sym) instead. * Deprecat ruby.rb, which was a sort 1.9 compatibility layer. * 22 Major Enhancements * Changed File#rewrite to not use the in-place change of the string. * Renamed Class#to_pathname and #to_methodname to #pathize and #methodize. * Removed Console:: namespace for ANSICode. * Moved Mentalguy's lazy.rb to core! * Added Indexable and Stackable to core. * BasicObject is now just a synonm for BlankSlate unless Ruby 1.9. [major] * Moved Indexable and Stackable to core. * Renamed arguments.rb and CLI::Arguments to argvector.rb and Argvector. * Added optional argument to Dictionary#first and #last. * Moved binding/opvars from core to more. * 19 Minor Enhancements * Improved File#rootname --it is now more robust. * Made FileUtils#whereis a module_function again. * Created Lore library to house extensions to Ruby's standard library. * Re-added facets class files (eg. facets/string) and are now dynamic. * Added block to Array#index. * This is one of the few core overrides in Facets. * It is a feature already in Ruby 1.9. * Added Jim Weirich's BlankSlate class. * This is a temporary measure be compatible w/ AcitveSupport's BasicObject. * Split kernel/load.rb into require_all.rb and require_local.rb. * Split module/alias.rb up into alias_accessor, alias_module_function and alias_method_chain. * Renamed string/subtract to string/op_sub. Old name will remain for time being for compatability. [minor] * Moved style.rb to string/stylize.rb [minor] * Added warning to bytes to use RichUnits instead. * Updated warn line fore eventual deprecation of fileshell and arguments.* * Added facets-load.rb to allow old school cherry picking.* * Between 2.0 and 2.4 require 'facets' simply added core to LOAD_PATH. * Starting with 2.4 it loads all of core automatically instead. * facets-load.rb provides a way to use the old behavior. require 'facets-load.rb require 'kernel/with' require 'symbol/to_proc' * This adds the path to the end of LOAD_PATH to prevent any load conflicts. * 5 Bug Fixes * Fixed Time#hence changed years when changing months. * Fixed Time#hence to flip year correctly when adding months. * Hash#<< returns self * Fixed String#pathize. * Module#instance_method_defined? now only applies to public methods. * Administrative Enhancements * While not perceptible to an end user, there are now 3 divisions: lib/core, lib/lore, lib/more. * Modified script/test to display $LOAD_PATH before running tests. == 2.4.2 / 2008-08-12 Just some more of those great old work your ass off changes. Changes: * Major Enhancements * Added Ken Bloom's DictionaryMatcher class from Ruby Quiz #103. (Note this class will probably be renamed in the future.) * Changed File#rewrite to not use the inplace change of the string. * If you were using the function, change your code to use File#rewrite! instead. * Or, modify your code ot use the new behavior. * This change can make for a slippery bug, so be sure to check for it! * Moved live.rb to facets-live.rb. * Added kernel/instance method which provides a fluent interface to private object space. * 5 Minor Enhancements * Added sow generation forms. * Spilt Time#trunc into separate file. * Remove old log files --shouldn't version control these. * Added note to FileList to add glob options parameter. * Added optional argument to Dictionary#first and #last. * Other Enhancements * Move "lore" tests to test/lore (lore are extensions to Ruby's standard lib). * Added test/core, test/lore and test/more. * Added time/test_round.rb * Added array/recursively. * Added time/round. * Time#to_date makes the public (it already existed in Ruby!) * Fixed Time#hence to flip year correctly when adding months. * Work on documentation using new Sow system. * Moved meta.rb to more/kernel/meta.rb and merged facets/core.rb into facets.rb. * Added more/kernel directory --hey not every extension can be core. * Adjusted loadpath and moved lazy.rb to core! * Moved remaing files to subdirectory locations. * Moved most core libs to core/. * Move most more files to the more directory. * Added lore and more directories. * Added facets/core directory. Yes, I'm spiliting the lib again. * Loadpath will be used, so user inteface will stay the same. * Setup.rb will be adjusted to recognaize loadpath. * Removed Rope class. If anything this will have a separate project. * Moved setup.rb to script/setup. * This will either be replaced with configure/install scripts. * Or, depend on a separate ruby setup.rb project. * Added recorder.rb to consider in work directory. * Added admin directory. * Added "TO BE DEPRECATED" message to ruby.rb. * Added all methods from ruby.rb as individual core methods. * These are the methods that overlap with 1.9. * They are encased in 'unless RUBY_VERSION' caluses. * Imporved file/rootname --now much more robust. * Added Kernel#to_yamlfrag to yaml.rb as way to output yaml w/o the "---" header. * Perhaps not the most robust solution, but okay for now. * Maybe a poor name for the method, but you got a better one? * Made FileUtils#whereis a module_function again like it used to be. Because: (1) that seems to be the way most other FileUtils methods are (cd, mkdir, cp, ...) and the most obvious way that users would WANT to use FileUtils: FileUtils.whereis("ruby"). (2) I see module_function used in other comparible parts of Facets: UploadUtils, ConsoleUtils, ZipUtils, FileUtils#safe_ln, ... (3) My code that relied on the old module_function behavior was breaking What were you thinking changing it?? ;) == 2.4.1 / 2008-04-03 This release takes aim at improving compatability with ActiveSupport. It also reintroduces an improved paramix.rb. Changes: * 4 Major Enhancements * A much improved paramix.rb has been returned to the library. * There a no longer capitialize module methods at all. * Use Module#[] and mixin_params[] instead. * Deprecated behavior.rb. It was not robust. * Added basex.rb, for working in any encoding base using any character set (base62 is the default). * 3 Minor Enhancements * Comparing to ActiveSupport, found 63 extension clashes, but most are due to 1.9 features. The rest should be compatible. * Reatomized a number of Kernel and String methods. Reatomization is nearly complete. * Continued work on reatomizing core extensions (nearly complete now). == 2.4.0 / 2008-03-24 Facets 2.4 is a major step forward for Facets. It is perhaps the release that 2.0 should have been, but of course it took the actual 2.0 release to make 2.4 possible. Some annoyances you may have encountered in updating your code to 2.0 are now fixed. And from 2.4 on, Facets will now be settling down into simple refinement release cycles for a while. The main change under the hood is to bring everything up to the top lib/facets/ directory. No longer are the libraries sorted by category. I had done so for a long time to make it easier to track the various libs, but in the end it was only making it more diffcult to deal with build tools and packaging. For the end-user, the largest change is a new emphisis on: require 'facets' This is better than cherry-picking methods. It may seem counter- intuitive, but it actually proves more advantantages to do this for the sake of interoperability than the practice of cherry-picking. The reason is simply because others may have cherry-picked different methods, and those distinctions go unaccounted and untested. Also with this release, to bolster the use of require 'facets', some lack-luster extensions have been deprecated and namespace usage has been improved. In addition, we are getting very close to full ActiveSupport, and Ruby 1.9, interoperability. Expect this to be complete in the next minor release or two. Changes: * Enhancements * String#to_re and String#to_rx have swapped default behaviors. #to_rx escapes, #to_re does not. * The Console namespace is being deprecated. command.rb and arguments.rb now use CLI naemspace. * #compare_on and #equate_on are now "mixin methods" Comparable() and Equateable(). * Enumerable#product, #combintations and #permutations have change to be Ruby 1.9 compatible. * thread.rb, map_send, et al, block is passed to send instead of yielding on result. * namespace.rb has been renamed to methodspace.rb. * Ruby 1.9 defined a new Proc#curry method, so Facets version has been made compatible. * The old curry method is now called #partial, as in "partial application". * Deprecated interface.rb. Perhaps a better approach but nonetheless extraneous. * Deprecated paramix.rb. A better way is to use a capitialized methods. (Perhaps a lib for that?) * Brought back a few web related libs, htmlfilter.rb and cssfilter.rb in particular. * camelcase and snakecase are core extensions. For specialized styles use String#style in style.rb. * Renamed ArgVector to CLI::Arguments * Moved one_nine.rb to ruby.rb * Moved test/test_one_nine.rb to test/test_ruby.rb. * Updated requires for "one_nine" to just "ruby" b/c of backports to 1.8.7. * Added warning to Rick Kilmers's unit system. * Moving Rich Kilmers's units system to it's own package. * Three are alternate unit systems available and Facets should work with any of them. * Will keep a fair amount of the Time extensions though. * Moved nil/status.rb to nilstatus.rb * Got rid of Method#curry and Method#partial since they just convert to Procs. * Made op_esc.rb a separate module rather thanan extension. * Deprecated with_reader, with_writer and with_accessor for attr_singleton_reader, &c. * Deprecated Hash#pairs_at. Use Hash#slice instead from core. * Fixed the namespaces of some extensions. * Added prime directory and files. * Removed all "prime" extension files. * Move mattr to module. * Fixed require bug in time methods. * Reverted memomize.rb back to original code --will come back to later. * Added stylizer.rb to replace stylize.rb * Array #recursively is not only called #traverse. * Added case/stylize methods to more/facets/string. * Renamed more/string/facets/titlecase to captialize_all. * Added uri and xoxo tests. * Progressive work on memoize and elementor. * Functor no longer privatizes =, == and =~. * Properly split conversion.rb. * Some string methods extracted from stylize.rb. * Moved random.rb to more/. * Renamed namespace.eb to methodspace.rb. * Moved autoreload to more/facets/kernel. * Removed old curry.rb. * Added cgi.rb with some standard extensions. * Deprecated paramix.rb. * Added xmlhash.rb and returned uri.rb extensions to the library. * Added #method_name to Date class. * Remove cut-bases AOP, now in it's own library. * Converted compare_on.rb to Paramtric Mixins. * Split fileutils up into individual methods. * Renamed console.rb to what it should be consoleutils.rb. * Update to command.rb integrating MasterCommand and Command into a single class. * Added options back into multiglob_r. * Improved cloneable.rb to be a true deep dup/clone mixin using Ken Bloom's suggestion. * Added tasksystem.rb. * Added enumerable/combinations. * Added openhash and tracepoint. * Bug Fixes * Fixed bug with #peek in stackable. * Fixed bug in Kernel#object_hexid. * Fixed bug in multiglob_r so it will NOT follow symlinks. * Fixed test_keyize.rb. * Adminstrative Changes * This was a fairly large and fast-paced update, so unfortunately not all changes are listed this time. * Added ri generation to setup.rb. * Updated README and allowed doc/ to be included in package. * Finally completed removal of all embedded tests. * Organized all libs between core, more, class and mixin. == 2.3.0 / 2008-02-01 Amoung other changes with this release, cloneable.rb is now a true deep dup/clone mixin; tracepoint.rb returns to the library. Changes: * 4 Major Enhancements * Cloneable provides true deep cloning. * Moved hash_keyize.rb to CORE as hash/keyize.rb. * Added tracepoint.rb back to the library. * Added hash/collate. * 3 Bug Fixes * Fixed multiglob_r bug, so it will NOT follow symlinks. * Added a couple of missing binding requires. * Fixed test_keyize.rb. * 6 Admistrative Changes * Reorganized library into smaller groups: core, more, class and mixin. * Remove admin/svn subdir. * Remove admin/log. * Add admin tasks. * Moved admin tasks to admin directory. * Added admin directory. == 2.2.1 / 2007-12-22 This release get rid of the underlying methods subdir. All method redirects are now in core, to ensure there are no more name clashes. Changes: * Method Renames * Moved string/format.rb to string/wrap.rb. * Updated String#brief. * Moved binding/cflow.rb to caller.rb. * Moved core hash/keyize to more. * Other Enhancements * Fixed up binding extensions. * Administrative Adjustments * Got rid of methods subdir. All method redirects are in core/. * Moved doc/wiki to apiwiki b/c of Rubyforge's wiki. * Removed doc/api dir. * Added wiki. * Renamed a couple test tasks. * Update per-module/class files. * Moved methods and groups task to trash. * Added test class/remove_descendents.rb. * Added all remaining per-method require libs from methods/ (will need to wrok through these over time). * Added trash work directory. * Adjust text according to per-method file changes. * All hash method, but the conversion methods, are now represented in core/facets/hash. * Added a few more Hash per-method files. * Add per-method libs for hash. * Updated facets/string.rb. * Renamed ROLLRC to facets.roll. == 2.2.0 / 2007-12-13 This release provides improved rdocs and prepares facets for use with Ruby 1.9. It also adds Matthew Harris' duration.rb library. Bug thanks to Matthew! Changes: * Additions * Added Matthew Harris' Duration class. * Added Hash#slice and Hash#except (didn't we have this before?) * Added registerable.rb, updated history. * Added #include_as to facets/namespace.rb. * Added op.rb to string.rb. * Added String/op.rb with String#- method. * Method Renames and Reorganizations * The name Array#unzip didn't makes sense, it was renamed to #modulate (though #collate seems better?) * Renamed Enumerable#collate to #mash (Map hASH); #collate and #graph remain aliases for the time being. * Renamed accessor #attributes to #instance_attributes. * Renamed Enumerable #collate to #mash. (old name, along with graph, will be an alias for time being) * Divided enumerable/collect into split.rb and each.rb as well. * Moved mapsend.rb to thread.rb. * Updated mapsend.rb to focus on threads. * Moved continuation extensions to more lib. * Deprecations * Deprecated Module#include_and_extend. Just use both silly. * More lib pp_s.rb has been removed. Use #pretty_inspect instead. * Removed continuation from core. * Removed pp_s.rb (use pretty_inspect) add continuation.rb. * Remove kernel/require_esc.rb. * Other Enhancements * integer/bitmask.rb has changed a bit --pun intended ;) Deprecated some methods and now use "~" instead of "-" to clear bits. * Split binding extensions up a bit more finely --eval.rb sprouted here.rb, self.rb and defined.rb. * Move Time#stamp out of conversion.rb and into time/ dir, and remove to_s alias. * Preliminary addition of Matthew Harris' excellent duration.rb lib (will integrate with times.rb better in future). * Minor edit to basicobject.rb in light of 1.9. * Minor adjustments to lazy.rb to fix warnings by Ruby 1.9. * Added if clauses to handle upcoming Ruby 1.9 gracefully. Facets should now be just about ready for use with 1.9. * Documentation Enhancements * A lot of rdoc updates to core extensions --as promised ;) * Just about every method now has at least a brief explinaiton and an example. * Administrative Adjustments * Moved task/config.yaml to meta/ per new Ratch. * Moved task/special to task/doc. * Updated todo list (in dev/). * Copied log/history.rd to CHANGES. * Removed log/history.rd and log/todo.rd * Fixed stylize.rb for use with 1.9 (fixed case statement). * Separated kernel/returning, now that #tap will be in 1.9. * Updated facets.rb for use with 1.9. * Separated time/stamp.rb. * Divided binding up into a few more pieces. * Fixed kernel/instance to play nice with 1.9. * Added test for string/op.rb. * Added test_collect.rb split-offs and test_mash inplace of test_collate. * Cleanup test headers. * Added 1.9 check in continuation/create.rb. * Add a couple new task for rdoc gen. * Added nbsp to quickopts task. * Work on website using siteparts. == 2.1.3 / 2007-11-28 This release fixes four bugs --one being fairly serious, as it prevented require 'facets' from working at all. Changes: * 4 Bug Fixes * Fixed oddity in Enumerable/collate. * Fixed issue that prevented loading of facets.rb. * Array#to_h used flatten, but it needed to be flatten(1). * Move core/main.rb back to core/facets.rb as it conflicts with lib in more/. == 2.1.2 / 2007-11-22 Changes: * Additions * Added Exception#details. * General Enhancements * Dir::multiglob no longer handels -/+ modifiers. Use FileList instead. * Administrative Adjustments * Fixed task/install script. * Improved task/changes. == 2.1.1 / 2007-11-16 Changes: * Additions * Added kernel/ergo.rb. * Added pp_s.rb (Questionable addition, but we'll leave it for now.) * Added validation.rb. This is here for Nitro's sake --better techinques may replace it in the future. * Added Console::Logger to logger.rb (may be separated in future). * Added option arity to command.rb. * Deprecations * Removed tracepoint.rb. * Bug Fixes * Fixed bug in command.rb that clobbered options. * Fixed options bug in command.rb. == 2.1.0 / 2007-11-10 Major changes include a new and much-improved command.rb, a new BiCrypt class for simple two-way crypotgraphy, as well as attr_reader!, attr_writer! and attr_accessor! for flag attributes, plus alias_xxx methods for all attr_xxx methods. Changes: * Additions * Added BiCrypt class for simple two-way encryption. * module/attr.rb now has attr_reader!, attr_writer! and attr_accessor! * All attr_xxx methods have coresponding alias_xxx methods. * Added UniversalOptions module. * Added "tester" attribues attr_xxx!. Also added alias_xxx for all attr_xxx methods. * Enhancements * command.rb has been completely rewritten. The API has changed completely! * There is no longer a Commmand::Optoins class. Use Console::Arguments instead. * Moved common alias methods from attr.rb to alias.rb. * MasterCommand now passes (args, opts), until 1.9 is main stream. * Cleaned up enumerable/permutation.rb * Added -q option to zip method in ZipUtils. * Ok. #p is back. This will in fact be in 1.9, so we're good. * Bug Fixes * Fixed bug in Enumerable#cluster_by which returned nil instead of []. * Fixed minor bug in arguments.rb that prevented proper repeat parameters. * Fixed bug in to_console. * Fixed bug in enumerable/cluster_by (returned nil instead of []). * Fixed bug in Hash#- Thanks to Xavier Shay. * Fixed to_h in Command::Options * Admin Changes * Added dev/test * Renamed RELEASE to WHATSNEW * Added injecting test and cleaned up. * Added comment for potential future #is. * Added top-level log directory. * Remove #q reference from RELEASE. * Cleanup of test_initializer.rb. == 2.0.5 / 2007-11-07 Minor release that fixes a couple of bugs and adds the last of adopted methods from Gavin Sinclair's Extensions project. Also, renamed #p to #q, because of multiple args problem. I don't know how Ruby 1.9 plans to handle multiple args. Will deprecate for 1.9 anyway so doesn't matter much. Changes: * Additions * Added final methods Gavin Sinclair's Extensions project. (Noah Gibbs) * General Improvements * Made #alias_method_chain compatible with current ActiveSupport version. * Rename #p to #q, because of multiple args problem. * Allow Class#initializer to return the attribute names. * Bug Fixes * Fixe return bug in hash/op.rb. * Fixe bug with Dictionary#initialize. * Fixe bug with Hash#-. (Xavier Shay) * Admin Adjustments * Fixed package name in icli.yaml. * Added name field to meta/icli.yaml. * Added meta/icli.yaml. * Added a RELEASE file to hold current release notes. * Added log task. * Added changelog file in doc/log/. == 2.0.4 / 2007-11-04 Changes: * Unsorted Changes * Up'd version to 2.0.4. * Update task/groups. * Removed extest task. We will no longer need it. * Minor update to rdoc.yaml. * Renamed old changelogs. == 2.0.3 / 2007-11-02 Changes: * Unsorted Changes * Touch up to methods task. * Update rsync filter * Minor updates fixing issues highlighted by running crosstest. * Many minor bug fixes after running against crosstest. * Added usage support for __foo options. * Fixed a many a test after running against crosstest. * Removed load task. It did not isolate the libs, so wasn't effective. * Added a number of new tasks. * Rename SMTP_TLS to Smtp_tls for Rdocs. * Moved rdoc.yaml to config/. * moved task/config to task/config/general. * Update tasks. 2007-11-01 transami Changes: * Unsorted Changes * Added array/only, symbol/to_proc (where did it go?) and hash/select. * Update roll file. * Moved test_command_options to test_command. * Update dictionary test to check dup and autohash. * Fixed autohash and dup bugs. * Verbatim support for Rails' version of #alias_method_chain. * Remove site/ directory. * Moved rsync filter up too. * Moved doc/site/ up to doc/. * Added javascript directory to doc/. * Updates across the board. * Updates to stylize and command.rb. * Made facets.rb a shortcut to facets/facets.rb (this is for Rolls, better way?) * Oh smack. Lots of stuff fixed. * Remove version.txt. No longer needed. * Removed meta/project.yaml, replaced by facets roll file. * Modifications to command.rb, snapshot and rbsystem. * Merged command.rb and command_options.rb into command.rb. * Added to_data aliases to snapshot.rb * Minor additions to rbsystem. Rather than System, maybe Ruby? * Removed embedded test from overload.rb. * Allow OpenStruct#initialize to take a setter block. * Downloader needs 'wb' flag rather then just 'w'. * Fixed typo and removed embedded test. * Fixed bug in command_options.rb, putting the class back in the Console namespace. * improved module/traits.rb == 2.0.2 / 2007-10-08 Changes: * Administrative Changes * Cleaned up some test and updated version to 2.0.2 * Update methods to eleminate duplicate file names between lib/core and lib/methods == 2.0.1 / 2007-10-06 Changes: * Unsorted Changes * updated version to 2.0.1 * minor bugs fixes * update methods task to display each file as it process it * added benchmarks for some enumerable methods. * moved demo/bench/bench_factorial to an demo/bench/integer subclass * added Erik Veenstra to AUTHORS for work on enumerable/group_by and cluster_by * minor improvement to test task to specifically read test_*.rb files * removed enumerable/partition.rb * move enumerable/partition.rb methods to collect.rb. * Improved Integer#of. * Minor improvements to collect.rb and partition.rb * Deprecated nonuniq!, bug fixed cluster_by and aliased group_by and partition_by. * Renamed Enumerable#partition_by to group_by (like Ruby 1.9) and fixed bug in cluster_by. == 2.0.0 / 2007-10-02 Changes: * General Enhancements * Added Oliver Renaud to the AUTHORS list (oops!) * Bug Fixes * Fix requires in `cut.rb` and `attributes.rb`. * Fix `String#brief` in `format.rb`. * Unsorted Changes * removed 1stClassMethod from "more" docs * removed 1stClassMethod as a rdoc target (now in Core target) * update install and rdoc tasks * moved string/test_index.rb to string/test_nchar.rb * updated indexable tests * update string.rb to include string/nchar.rb * moved index.rb to nchar.rb * clean up string/index.rb * moved facets.rb to fore directory * add comment to groups task * added groups task * updated all extrension group files (array.rb, binding.rb, etc.) * uncapitalize meta files * update methods task a bit more, plus related configuration * updated methods task * removed lib/core --this is generated content (may be renamed too) * added load and stats tasks * update install task --this replaces setup b/c of Facets' special install needs * update project file * removed lib/facets * moved remaining libs to fore (will later consider an additional subdivision) * move facets/fore to fore/facets * move facets/more to more/facets * added ;ob/core, more and fore * move memorize * removed io and net directories * moved io/redirect.rb to more/ioredirect.rb and net/smtp_tls.rb and net/uploadutils.rb libs to more too. * few more libs moved to more/ directory * moved all the most obvious more libs to the more directory * moved fore "grouping" libs to fore directory * moved "fore" libs to fore directory * create for and more directories (yes, you know what's coming ;) * renamed remain.rb (was main_as_module.rb) to just main.rb * improved rdoc task and project.yaml file * better docs for OpenObject * improved method hiding * documentation touch ups * fixes for conversion.rb rather than conversions.rb * updated to website docs * moved demos to demo/sample * added bench and sample dir to demo * moved spy.html to light.html * menum change to webpage, fixed core doc link * moved metadata files to meta/ (info/ or box/ would be better?) * updated test_conversion.rb for to_h/to_hash * reverse_each instead of each for after advice in advice.rb * final fix to to_h/to_hash discrepency * added a Path and Root features to Pathname (good idea?) * update advice.rb test and moved old cut test to dev/scrap * updated advice; removed preinitialize.rb to trinkets project (it was too expiremental) * command_filter.rb needs to considered/developed; moved to dev/new/ * fixed interface.rb fo singelton methods * updates to tests * whole lot of small bug fixes * add tests to revision control * removed old cut test (moved to dev/scrap) * working on tests * added read.rb (taken from readwrite.rb) * split readwrite.rb into read.rb and write.rb * remove string/unpack.rb, offset can be had using '@' format instead * renamed conversions.rb to conversion.rb, fixed some requires * improved attr.rb * some cleanup of enumerable extensions * setup annotations demo * add non-embedded tests * finally brough over toadcode prototype.rb and cleaned it up enough to be useful * removed annotations subdir * moved annotations/ann.rb and attr.rb to annotations.rb and attributes.rb * remove annotations.rb * moved annotations/settings.rb up a dir * remove settings.rb * chnaged multiton_id(e) to multiton_id(*e,&b) * updated test task * added Christoph Rippel to authors lists * added doc header to new multiton class * update to new version of multiton * playing around with multiton2.rb * renamed dev/try to dev/new * created dev/old to temporarily house old versions of libs that have been replaced. * fixed quick.html documentation * used old wiki.gif as email.gif instead * fixed config.yaml publish entry * some minor updates to index.html * moved site to doc/site * update to publish task * updates of tasks * added kernel/report.rb to hold debug/warn extensions. * renamed reporting.rb to silence.rb * update reporting.rb (created report.rb from it) * task work * clean up dev finis * cleanup dev just a bit more * continue cleanup of dev directory * moved dev/twiki to misc/ * removed dev/core * moved require_directory.rb to misc/ * added dev/misc for code scraps that might be useful but are not straight lib or task code * more dev changes * organize dev better * cleanup of dev continues * cleanup of dev dir * clean up dev dir more * some cleanup of dev directory * almost completed advice lib * added comment about possible update * deprecate instance_send and instance_map * work on rdoc task * work on rdoc task * added dev/cut dir * no reason to track .config * clean up trunk * added todo comment * added advice.rb to replace old aspects.rb * removed aspects.rb (sucked), added prototype.rb (infancy) and adjusted to class_extension.rb * removed #to_roman (now part of the English project) * cont. work on aop and cuts * fixed IMG tag bug * added yaml.rb * move #here convenience method to binding/eval (separate?) * added in order to remove kernel/misc.rb * consolidate string/regesc * added module/methods * updates to include and attr * fixed Range#umbrella * more organization of docs * orginizing docs * update val.rb * added proc/fn.rb (from kernel/misc.rb) and fixed typo in compose.rb * moved misc.rb to val.rb * better organization of some kernel methods * moved #here alias to eval.rb * minor updates and some bug fixes (modspace what broke) * removed file/yaml.rb in favor or just yaml.rb * moved this to facets/yaml.rb * work on aop system * Added aop.rb, and cut.r and recursive.rb * moved cut.rb to dev (old version will be deprecated) * added to_hash to Dictionary, and minor mods to others * oops, no need for enumerator directory * moved threaded_send.rb to mapsend.rb * moved threaded_send out of enumerable/ dir * updates to elementor.rb * merged instance_map into threaded_send * removed map_send * merging map_send with threaded_send * cont work on elementwise methods * divide elementwise functions betwee two libs * uniq.rb is merged into count.rb * removed count.rb (uniq.rb will become count.rb) * continued refinement of enumerable extensions * general improvements to the organization of enumerable extensions * removed facets/cli dir * moved all cli libs from facets/cli to facets/ * moved cli support files to facets locations * moved cli lib to facets main (also modified functor) * renamed hash/reverse to hash/merge (it contains #reverse_merge) * remove instance_intercept (moced to Trinkets project) * continued modification of those tasky tools * removed lib/more (this is it!) * moved M-Z of more/facets to facets (this is it!) * moved A-L of more/facets to facets (this is it!) * removed lib/core (this is it!) * moved lib/core/facets.rb to lib/facets.rb (this is it!) * moved lib/core/facets to lib/facets (this is it!) * added file/yaml.rb * added a list of libraries considered "core" * continued work on build tools * change tools for core/more convergence (so help us god!) * added conversion requirement to some core libs * update methods task * update quick.html to mirror rdoc changes --still needs work though * remove old rdoc task * added rdoc section (minimal) to tool/config.yaml * nope. remove site/rdoc * add rdoc dir, should we? * remove site/rdoc in preperation for new way * facets.rb belongs to core/ * renamed some doc files * removed src/core * move src/core/lin to lib/core * added kernel/constant * remove src/core/web * moving more of core to top-level (svn sucks!) * moving core support files to top-level * removed src/more * move src/more/lib to lib/more * made lib dir (to replace src) * added settings.rb which points to annotations/settings.rb * moved svn to annotations/ subdir * moved dev files to top-level as part of more transition * temporarily removed dev/more * moved annotations demo to demo dir * added demo folder * add dev/more * remove struct again! (stupid svn) * moved file to top-level doc as part of more transisiton * bullshit svn crap * ann moved back to more (strongly considering annotations for it's own project) * build moved back to more * aop moved back to more * cast moved back to more * crypt moved back to more * exts moved back to more * file moved back to more * meta moved back to more * misc moved back to more * model moved back to more * struct moved to back to more * moved sync back to more * moved commandoptions.rb to command_options.rb * rewrote command and command options libs * initial Subversion import == 1.8.54 / 2007-03-21 The following list of changes also includes changes from intrim releases, `1.8.51 / 2007-02-19`, `1.8.49 / 2007-02-16`, `1.8.20 / 2007-02-06` and `1.8.8 / 2007-01-31`. Unfortuantely the transition form darcs to git, led to some information loss in this regard. Changes: * Unsorted Changes: * added reqiure to ostruct.rb test * fix to command.rb's initializer * fixed bug with times.rb beginning_of_year and beginning_of_month * replaced pqueue and heap with new working class (thanks to Olivier Renaud) * fixed bug in ormsupport.rb (this will be moved out of facets in next release) * added empty? to dictionary (removed old subclass of Hash) * significant improvements to command.rb thanks to Tyler Rick * added tests to elementwise and tap * fixed test for elementwise and op_tilde_self * added enumerable/map_send * added thread_map and thread_map_send thanks to greg * added operator "~@" for enumerable/elementwise * added more/consoleutils.rb * added string/cleave * added capitalize_all thanks to Richard Laugesen * cartesian_product is an alias of enumerable/cart * added array pad thanks to Richard Laugesen * added kernel/tap * fixed test/unit load issues * converted facet/ requires to facets/core or facets/more as needed * further improvements to arguments.rb (looking good!) * improved symbol/self/generate * bug fix kernel/autoreload arguments needed to be in opposite order * add to_xoxo * removed bad character codes in multiplier.rb * used yaml to allow json.rb to work for all object in general * improvements to functor (note: is to_a and to_proc okay?) * add test to string/bytes.rb * bug fix to nilclass/op_cmp * fixed enumerable/op_pow to use enumerable/cart * added array/op_div * adjustments to xmlbuilder and htmlbuilder dur to buildingblock changes * improved buildingblock.rb * simplified interface of arguments.rb (still a little more to do) * improvements/simplifications to Dir.multiglob * added new authors to list * fixed misspelling of behavior.rb (was bahvior.rb) * removed #own from base list in facets.rb (really need a standard for "singleton class") * minor adjustments to uploadutils * fixed bug in aspects.rb that would not handle args of wrapped method * Symbol#to_s optimization, had to remove freeze * updates to fileutils/stage (stage worth keeping?) * update to credits * fix bug in kernel/ask, returns more than one character * cleanup of enumerbale/graph (no effective change) * new super fast enumerable/cart by Thomas Hafner (replaces #cross) * improved multiglob rountines (accept '+' and '-' prefixes) * No longer will track project file via scm until it settles * fixed bug in attr_tester, thanks Dov! * added weekdays to times.rb thanks to Ryan Platte and Dave Hoover * improvements to dictionary.rb (no longer a subclass of Hash) thanks Jan! * re-replace openhash with openobject * improvements to ann.rb and ann_attr.rb. works, yea! * fixed bug in string/singular.rb * changed enumerable/cross into enumerable/cart and cartesian_product * openobject returns (openhash was a bad name, thanks george) * moved enumerable/cross to enumerable/cart (cartesian_product) == 1.8.0 / 2007-01-24 The list of changes also includes intrim releases `1.7.46 September 8, 2006`, `1.7.38 August 31, 2006`, and `1.7.30 August 23, 2006`. Changes: * Additions * Add facets/automatic.rb, very cool, albiet experimental, way to load core methods automatically! * added hash/insert; like store but only if key isn't already present * added module/include_and_extend * added File::mulitglob_sum; accumulates file patterns, and accepts '+' and '-' prefixes * added module/module_method; like module_function but makes method public * added module/include_function_module; attempts to properly include one function_module into another * kernel/yaml convenience method for YAML::load * added kernel/supress; supress errors while executing a block (nice DHH!) * added symbol/chomp, like string#chomp * added proc/to_h; converts an assignment proc into a hash * proc/bind; bind a proc to an object, returning a method * added module/prepend; provides dyanamic method wraps for modules, and static wraps for classes * added module/new; use a module as if it were a class * added module/alias_accessor * kernel/instance_class; yet anouther meta_class name, but a more sensicle name this one * added kernel/populate; populates an object's inst. vars from a hash or assingment block * added kernel/daemonize; one last thanks to DHH! * added enumerable/injecting; like inject but automatically returns the memo from the block * added kernel/object_send, a true public-only send method * added kernel/silence_stream; output to null device; thanks DHH! * added kernel/instance_values, thanks DHH! * added Config:inspect for rbconfig * added hash/pairs_at (aking to values_at) * added _why's metaid methods (meta_class, meta_eval, etc.) * added kernel/enable_warnings to complement silence_warinings * added integer/to_roman * added logical operators for hash (and/or) * array/to_path convert ans array to a path string * array/index takes a block * added fileutils/compress; very simple convenience methods for archiving folders * added fileutils/stage adn staged, a means of transfering files accoring to preset rules * added kernel/ask, simply command to get console input * added populate.rb, mixin for classes that need on a basic initializer * added version_number.rb (a specialized tuple) * added uploadutils.rb * added Joel VanderWerf's great script.rb script * added Austin's minitar.rb --it's just too damn useful! * added htmlfilter.rb very nice html escape class * added dependency.rb, allwos method to have dependend execution (like rake tasks) * added arguments.rb this is for parsing console command arguments * add new version of annotations: ann.rb and ann_attr.rb * added File::yaml? to roughly detect if a file is a yaml file * Renamed Features * Rename #superior to #super_at. * OpenObject = OpenHash (OpenObject will eventually be deprecated) * renamed quaclass to qua_class * renamed openobject to openhash !!! * Deprecations * had to remove taskable.rb for now (implementation won't work as toplevel include) * deprecated (yored) kernel/own, yet another term for the singleton class * removed dataobject.rb (was never used) * deprecated (yored!) module/inject; what a silly method * deprecated kernel/require_facet (no longer needed) * Bug Fixes * Fix enumerable/partition_by. * memoize should now work at toplevel * minor bug fix to httpaccess * General Enhancments * Add buildingblock.rb, replacing builderobject.rb. * HtmlBuilder and XMLBuilder aer now based on BuildingBlock * adjust require for "yored" files * minor improvements to basic object (object_self to access kernel methods) * ostuct adjustment, use #instance_delegate to get underneth the open access * module/include_as is now based on module/namespace (thanks Pit!) * minor adjustments to methods for (class<=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: *30626180 - !ruby/object:Gem::Dependency name: qed requirement: &30612740 !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: *30612740 - !ruby/object:Gem::Dependency name: detroit requirement: &30594700 !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' type: :development prerelease: false version_requirements: *30594700 description: Facets is the premier collection of extension methods for the Ruby programming language. Facets extensions are unique by virtue of thier atomicity. They are stored in individual files allowing for highly granular control of requirements. In addition, Facets includes a few additional classes and mixins suitable to wide variety of applications. email: - transfire@gmail.com executables: [] extensions: [] extra_rdoc_files: - RUBY.txt - HISTORY.rdoc - README.rdoc - NOTICE.rdoc files: - .ruby - .yardopts - lib/core/facets/applique/file_helpers.rb - lib/core/facets/array/after.rb - lib/core/facets/array/before.rb - lib/core/facets/array/collapse.rb - lib/core/facets/array/collisions.rb - lib/core/facets/array/combination.rb - lib/core/facets/array/commonality.rb - lib/core/facets/array/conjoin.rb - lib/core/facets/array/contains.rb - lib/core/facets/array/delete.rb - lib/core/facets/array/delete_unless.rb - lib/core/facets/array/delete_values.rb - lib/core/facets/array/divide.rb - lib/core/facets/array/duplicates.rb - lib/core/facets/array/each_pair.rb - lib/core/facets/array/each_value.rb - lib/core/facets/array/entropy.rb - lib/core/facets/array/extract_options.rb - lib/core/facets/array/from.rb - lib/core/facets/array/index.rb - lib/core/facets/array/indexable.rb - lib/core/facets/array/median.rb - lib/core/facets/array/merge.rb - lib/core/facets/array/mode.rb - lib/core/facets/array/nonuniq.rb - lib/core/facets/array/not_empty.rb - lib/core/facets/array/occurent.rb - lib/core/facets/array/only.rb - lib/core/facets/array/op_pow.rb - lib/core/facets/array/pad.rb - lib/core/facets/array/peek.rb - lib/core/facets/array/permutation.rb - lib/core/facets/array/poke.rb - lib/core/facets/array/probability.rb - lib/core/facets/array/product.rb - lib/core/facets/array/pull.rb - lib/core/facets/array/recurse.rb - lib/core/facets/array/recursively.rb - lib/core/facets/array/rotate.rb - lib/core/facets/array/select.rb - lib/core/facets/array/splice.rb - lib/core/facets/array/split.rb - lib/core/facets/array/store.rb - lib/core/facets/array/thru.rb - lib/core/facets/array/traverse.rb - lib/core/facets/array/uniq_by.rb - lib/core/facets/array.rb - lib/core/facets/binding/__callee__.rb - lib/core/facets/binding/__method__.rb - lib/core/facets/binding/call_stack.rb - lib/core/facets/binding/caller.rb - lib/core/facets/binding/callstack.rb - lib/core/facets/binding/defined.rb - lib/core/facets/binding/eval.rb - lib/core/facets/binding/local_variables.rb - lib/core/facets/binding/op.rb - lib/core/facets/binding/op_get.rb - lib/core/facets/binding/op_set.rb - lib/core/facets/binding/self.rb - lib/core/facets/binding/with.rb - lib/core/facets/binding.rb - lib/core/facets/boolean.rb - lib/core/facets/class/descendants.rb - lib/core/facets/class/hierarchically.rb - lib/core/facets/class/methodize.rb - lib/core/facets/class/pathize.rb - lib/core/facets/class/preallocate.rb - lib/core/facets/class/singleton.rb - lib/core/facets/class/subclasses.rb - lib/core/facets/class/to_proc.rb - lib/core/facets/class.rb - lib/core/facets/comparable/at_least.rb - lib/core/facets/comparable/at_most.rb - lib/core/facets/comparable/bound.rb - lib/core/facets/comparable/cap.rb - lib/core/facets/comparable/clip.rb - lib/core/facets/comparable/cmp.rb - lib/core/facets/comparable/op_get.rb - lib/core/facets/comparable.rb - lib/core/facets/denumerable.rb - lib/core/facets/dir/ascend.rb - lib/core/facets/dir/descend.rb - lib/core/facets/dir/each_child.rb - lib/core/facets/dir/multiglob.rb - lib/core/facets/dir/parent.rb - lib/core/facets/dir/recurse.rb - lib/core/facets/dir.rb - lib/core/facets/enumerable/accumulate.rb - lib/core/facets/enumerable/cluster_by.rb - lib/core/facets/enumerable/collect_with_index.rb - lib/core/facets/enumerable/compact_map.rb - lib/core/facets/enumerable/count.rb - lib/core/facets/enumerable/defer.rb - lib/core/facets/enumerable/each_by.rb - lib/core/facets/enumerable/each_with_object.rb - lib/core/facets/enumerable/every.rb - lib/core/facets/enumerable/ewise.rb - lib/core/facets/enumerable/exclude.rb - lib/core/facets/enumerable/expand.rb - lib/core/facets/enumerable/filter.rb - lib/core/facets/enumerable/find_yield.rb - lib/core/facets/enumerable/frequency.rb - lib/core/facets/enumerable/graph.rb - lib/core/facets/enumerable/group_by.rb - lib/core/facets/enumerable/hashify.rb - lib/core/facets/enumerable/incase.rb - lib/core/facets/enumerable/map_by.rb - lib/core/facets/enumerable/map_detect.rb - lib/core/facets/enumerable/map_send.rb - lib/core/facets/enumerable/map_with.rb - lib/core/facets/enumerable/map_with_index.rb - lib/core/facets/enumerable/mash.rb - lib/core/facets/enumerable/modulate.rb - lib/core/facets/enumerable/none.rb - lib/core/facets/enumerable/occur.rb - lib/core/facets/enumerable/one.rb - lib/core/facets/enumerable/per.rb - lib/core/facets/enumerable/purge.rb - lib/core/facets/enumerable/recursively.rb - lib/core/facets/enumerable/sum.rb - lib/core/facets/enumerable/take.rb - lib/core/facets/enumerable/uniq_by.rb - lib/core/facets/enumerable/visit.rb - lib/core/facets/enumerable/zip_map.rb - lib/core/facets/enumerable.rb - lib/core/facets/enumerator/fx.rb - lib/core/facets/enumerator.rb - lib/core/facets/exception/detail.rb - lib/core/facets/exception/error_print.rb - lib/core/facets/exception/raised.rb - lib/core/facets/exception/suppress.rb - lib/core/facets/exception.rb - lib/core/facets/file/append.rb - lib/core/facets/file/atomic_id.rb - lib/core/facets/file/atomic_open.rb - lib/core/facets/file/atomic_write.rb - lib/core/facets/file/create.rb - lib/core/facets/file/ext.rb - lib/core/facets/file/null.rb - lib/core/facets/file/read_binary.rb - lib/core/facets/file/read_list.rb - lib/core/facets/file/rewrite.rb - lib/core/facets/file/rootname.rb - lib/core/facets/file/sanitize.rb - lib/core/facets/file/split_all.rb - lib/core/facets/file/split_root.rb - lib/core/facets/file/write.rb - lib/core/facets/file/writelines.rb - lib/core/facets/file.rb - lib/core/facets/filetest/absolute.rb - lib/core/facets/filetest/contains.rb - lib/core/facets/filetest/relative.rb - lib/core/facets/filetest/root.rb - lib/core/facets/filetest/safe.rb - lib/core/facets/filetest/separator_pattern.rb - lib/core/facets/filetest.rb - lib/core/facets/fixnum.rb - lib/core/facets/float/round.rb - lib/core/facets/float.rb - lib/core/facets/functor.rb - lib/core/facets/hash/alias.rb - lib/core/facets/hash/argumentize.rb - lib/core/facets/hash/at.rb - lib/core/facets/hash/autonew.rb - lib/core/facets/hash/collate.rb - lib/core/facets/hash/count.rb - lib/core/facets/hash/data.rb - lib/core/facets/hash/dearray_values.rb - lib/core/facets/hash/deep_merge.rb - lib/core/facets/hash/delete.rb - lib/core/facets/hash/delete_at.rb - lib/core/facets/hash/delete_unless.rb - lib/core/facets/hash/delete_values.rb - lib/core/facets/hash/diff.rb - lib/core/facets/hash/except.rb - lib/core/facets/hash/graph.rb - lib/core/facets/hash/insert.rb - lib/core/facets/hash/inverse.rb - lib/core/facets/hash/join.rb - lib/core/facets/hash/keys.rb - lib/core/facets/hash/mash.rb - lib/core/facets/hash/new_with.rb - lib/core/facets/hash/op.rb - lib/core/facets/hash/op_add.rb - lib/core/facets/hash/op_and.rb - lib/core/facets/hash/op_mul.rb - lib/core/facets/hash/op_or.rb - lib/core/facets/hash/op_push.rb - lib/core/facets/hash/op_sub.rb - lib/core/facets/hash/recurse.rb - lib/core/facets/hash/recursively.rb - lib/core/facets/hash/rekey.rb - lib/core/facets/hash/replace_each.rb - lib/core/facets/hash/reverse_merge.rb - lib/core/facets/hash/select.rb - lib/core/facets/hash/slice.rb - lib/core/facets/hash/stringify_keys.rb - lib/core/facets/hash/subset.rb - lib/core/facets/hash/swap.rb - lib/core/facets/hash/symbolize_keys.rb - lib/core/facets/hash/to_h.rb - lib/core/facets/hash/to_mod.rb - lib/core/facets/hash/to_options.rb - lib/core/facets/hash/to_proc.rb - lib/core/facets/hash/to_struct.rb - lib/core/facets/hash/traverse.rb - lib/core/facets/hash/update.rb - lib/core/facets/hash/update_each.rb - lib/core/facets/hash/update_keys.rb - lib/core/facets/hash/update_values.rb - lib/core/facets/hash/url_params.rb - lib/core/facets/hash/weave.rb - lib/core/facets/hash/zip.rb - lib/core/facets/hash.rb - lib/core/facets/indexable.rb - lib/core/facets/instance.rb - lib/core/facets/integer/bit.rb - lib/core/facets/integer/bitmask.rb - lib/core/facets/integer/even.rb - lib/core/facets/integer/factorial.rb - lib/core/facets/integer/multiple.rb - lib/core/facets/integer/odd.rb - lib/core/facets/integer/of.rb - lib/core/facets/integer/ordinal.rb - lib/core/facets/integer/roman.rb - lib/core/facets/integer.rb - lib/core/facets/kernel/__callee__.rb - lib/core/facets/kernel/__class__.rb - lib/core/facets/kernel/__dir__.rb - lib/core/facets/kernel/__get__.rb - lib/core/facets/kernel/__method__.rb - lib/core/facets/kernel/__set__.rb - lib/core/facets/kernel/as.rb - lib/core/facets/kernel/ask.rb - lib/core/facets/kernel/assign.rb - lib/core/facets/kernel/assign_from.rb - lib/core/facets/kernel/attr_singleton.rb - lib/core/facets/kernel/blank.rb - lib/core/facets/kernel/call_stack.rb - lib/core/facets/kernel/callstack.rb - lib/core/facets/kernel/case.rb - lib/core/facets/kernel/complete.rb - lib/core/facets/kernel/constant.rb - lib/core/facets/kernel/d.rb - lib/core/facets/kernel/deep_clone.rb - lib/core/facets/kernel/deep_copy.rb - lib/core/facets/kernel/demo.rb - lib/core/facets/kernel/disable_warnings.rb - lib/core/facets/kernel/eigen.rb - lib/core/facets/kernel/eigenclass.rb - lib/core/facets/kernel/enable_warnings.rb - lib/core/facets/kernel/equate.rb - lib/core/facets/kernel/ergo.rb - lib/core/facets/kernel/extend.rb - lib/core/facets/kernel/extension.rb - lib/core/facets/kernel/false.rb - lib/core/facets/kernel/here.rb - lib/core/facets/kernel/hierarchical_send.rb - lib/core/facets/kernel/identical.rb - lib/core/facets/kernel/in.rb - lib/core/facets/kernel/instance_assign.rb - lib/core/facets/kernel/instance_class.rb - lib/core/facets/kernel/instance_exec.rb - lib/core/facets/kernel/instance_send.rb - lib/core/facets/kernel/load_all.rb - lib/core/facets/kernel/load_relative.rb - lib/core/facets/kernel/maybe.rb - lib/core/facets/kernel/memo.rb - lib/core/facets/kernel/meta_alias.rb - lib/core/facets/kernel/meta_class.rb - lib/core/facets/kernel/meta_def.rb - lib/core/facets/kernel/meta_eval.rb - lib/core/facets/kernel/method.rb - lib/core/facets/kernel/no.rb - lib/core/facets/kernel/not.rb - lib/core/facets/kernel/not_nil.rb - lib/core/facets/kernel/object_class.rb - lib/core/facets/kernel/object_hexid.rb - lib/core/facets/kernel/object_send.rb - lib/core/facets/kernel/p.rb - lib/core/facets/kernel/presence.rb - lib/core/facets/kernel/present.rb - lib/core/facets/kernel/qua_class.rb - lib/core/facets/kernel/require_all.rb - lib/core/facets/kernel/require_relative.rb - lib/core/facets/kernel/respond.rb - lib/core/facets/kernel/returning.rb - lib/core/facets/kernel/silence.rb - lib/core/facets/kernel/silence_warnings.rb - lib/core/facets/kernel/singleton_class.rb - lib/core/facets/kernel/source_location.rb - lib/core/facets/kernel/super_method.rb - lib/core/facets/kernel/tap.rb - lib/core/facets/kernel/temporarily.rb - lib/core/facets/kernel/trap_chain.rb - lib/core/facets/kernel/true.rb - lib/core/facets/kernel/try.rb - lib/core/facets/kernel/val.rb - lib/core/facets/kernel/with.rb - lib/core/facets/kernel/writers.rb - lib/core/facets/kernel/y.rb - lib/core/facets/kernel/yes.rb - lib/core/facets/kernel.rb - lib/core/facets/lazy.rb - lib/core/facets/matchdata/match.rb - lib/core/facets/matchdata/matchset.rb - lib/core/facets/matchdata.rb - lib/core/facets/metaid.rb - lib/core/facets/method/composition.rb - lib/core/facets/method/memoize.rb - lib/core/facets/method/op_mul.rb - lib/core/facets/method/op_pow.rb - lib/core/facets/method.rb - lib/core/facets/module/abstract.rb - lib/core/facets/module/alias_accessor.rb - lib/core/facets/module/alias_method_chain.rb - lib/core/facets/module/alias_module_function.rb - lib/core/facets/module/all_instance_methods.rb - lib/core/facets/module/ancestor.rb - lib/core/facets/module/anonymous.rb - lib/core/facets/module/attr_class_accessor.rb - lib/core/facets/module/attr_setter.rb - lib/core/facets/module/attr_tester.rb - lib/core/facets/module/attr_validator.rb - lib/core/facets/module/basename.rb - lib/core/facets/module/can.rb - lib/core/facets/module/class.rb - lib/core/facets/module/class_accessor.rb - lib/core/facets/module/class_def.rb - lib/core/facets/module/class_extend.rb - lib/core/facets/module/class_inheritor.rb - lib/core/facets/module/class_method_defined.rb - lib/core/facets/module/copy_inheritor.rb - lib/core/facets/module/enclosure.rb - lib/core/facets/module/enclosures.rb - lib/core/facets/module/extend.rb - lib/core/facets/module/home.rb - lib/core/facets/module/homename.rb - lib/core/facets/module/housing.rb - lib/core/facets/module/include_as.rb - lib/core/facets/module/include_function_module.rb - lib/core/facets/module/instance_function.rb - lib/core/facets/module/instance_method.rb - lib/core/facets/module/instance_method_defined.rb - lib/core/facets/module/integrate.rb - lib/core/facets/module/is.rb - lib/core/facets/module/let.rb - lib/core/facets/module/mattr.rb - lib/core/facets/module/memoize.rb - lib/core/facets/module/method_clash.rb - lib/core/facets/module/method_space.rb - lib/core/facets/module/methodize.rb - lib/core/facets/module/modname.rb - lib/core/facets/module/module_def.rb - lib/core/facets/module/module_load.rb - lib/core/facets/module/nodef.rb - lib/core/facets/module/op.rb - lib/core/facets/module/op_add.rb - lib/core/facets/module/op_mul.rb - lib/core/facets/module/op_sub.rb - lib/core/facets/module/pathize.rb - lib/core/facets/module/preextend.rb - lib/core/facets/module/redefine_method.rb - lib/core/facets/module/redirect_method.rb - lib/core/facets/module/remove.rb - lib/core/facets/module/rename_method.rb - lib/core/facets/module/revise.rb - lib/core/facets/module/set.rb - lib/core/facets/module/singleton_method_defined.rb - lib/core/facets/module/spacename.rb - lib/core/facets/module/to_obj.rb - lib/core/facets/module/wrap_method.rb - lib/core/facets/module.rb - lib/core/facets/na.rb - lib/core/facets/nilclass/ergo.rb - lib/core/facets/nilclass/to_f.rb - lib/core/facets/nilclass.rb - lib/core/facets/numeric/approx.rb - lib/core/facets/numeric/close.rb - lib/core/facets/numeric/distance.rb - lib/core/facets/numeric/length.rb - lib/core/facets/numeric/negative.rb - lib/core/facets/numeric/positive.rb - lib/core/facets/numeric/round.rb - lib/core/facets/numeric/round_at.rb - lib/core/facets/numeric/round_to.rb - lib/core/facets/numeric/spacing.rb - lib/core/facets/numeric.rb - lib/core/facets/object/clone.rb - lib/core/facets/object/dup.rb - lib/core/facets/object/object_state.rb - lib/core/facets/object/replace.rb - lib/core/facets/object/try_dup.rb - lib/core/facets/object.rb - lib/core/facets/objectspace/classes.rb - lib/core/facets/objectspace/op_fetch.rb - lib/core/facets/objectspace/reflect.rb - lib/core/facets/objectspace.rb - lib/core/facets/proc/bind.rb - lib/core/facets/proc/bind_to.rb - lib/core/facets/proc/compose.rb - lib/core/facets/proc/curry.rb - lib/core/facets/proc/partial.rb - lib/core/facets/proc/to_method.rb - lib/core/facets/proc/update.rb - lib/core/facets/proc.rb - lib/core/facets/process/daemon.rb - lib/core/facets/process.rb - lib/core/facets/range/combine.rb - lib/core/facets/range/overlap.rb - lib/core/facets/range/quantile.rb - lib/core/facets/range/to_r.rb - lib/core/facets/range/umbrella.rb - lib/core/facets/range/within.rb - lib/core/facets/range.rb - lib/core/facets/regexp/arity.rb - lib/core/facets/regexp/multiline.rb - lib/core/facets/regexp/op_add.rb - lib/core/facets/regexp/op_or.rb - lib/core/facets/regexp/to_re.rb - lib/core/facets/regexp.rb - lib/core/facets/roman.rb - lib/core/facets/string/acronym.rb - lib/core/facets/string/align.rb - lib/core/facets/string/bracket.rb - lib/core/facets/string/briefcase.rb - lib/core/facets/string/bytes.rb - lib/core/facets/string/camelcase.rb - lib/core/facets/string/capitalized.rb - lib/core/facets/string/characters.rb - lib/core/facets/string/cleanlines.rb - lib/core/facets/string/cleave.rb - lib/core/facets/string/cmp.rb - lib/core/facets/string/compress_lines.rb - lib/core/facets/string/crypt.rb - lib/core/facets/string/divide.rb - lib/core/facets/string/each_char.rb - lib/core/facets/string/each_word.rb - lib/core/facets/string/edit_distance.rb - lib/core/facets/string/end_with.rb - lib/core/facets/string/exclude.rb - lib/core/facets/string/expand_tab.rb - lib/core/facets/string/file.rb - lib/core/facets/string/fold.rb - lib/core/facets/string/indent.rb - lib/core/facets/string/index_all.rb - lib/core/facets/string/interpolate.rb - lib/core/facets/string/lchomp.rb - lib/core/facets/string/line_wrap.rb - lib/core/facets/string/lines.rb - lib/core/facets/string/lowercase.rb - lib/core/facets/string/margin.rb - lib/core/facets/string/methodize.rb - lib/core/facets/string/modulize.rb - lib/core/facets/string/mscan.rb - lib/core/facets/string/natcmp.rb - lib/core/facets/string/nchar.rb - lib/core/facets/string/newlines.rb - lib/core/facets/string/op_div.rb - lib/core/facets/string/op_sub.rb - lib/core/facets/string/outdent.rb - lib/core/facets/string/pathize.rb - lib/core/facets/string/quote.rb - lib/core/facets/string/random_binary.rb - lib/core/facets/string/range.rb - lib/core/facets/string/range_all.rb - lib/core/facets/string/range_of_line.rb - lib/core/facets/string/rewrite.rb - lib/core/facets/string/roman.rb - lib/core/facets/string/shatter.rb - lib/core/facets/string/similarity.rb - lib/core/facets/string/snakecase.rb - lib/core/facets/string/splice.rb - lib/core/facets/string/squish.rb - lib/core/facets/string/start_with.rb - lib/core/facets/string/store.rb - lib/core/facets/string/subtract.rb - lib/core/facets/string/tab.rb - lib/core/facets/string/tabto.rb - lib/core/facets/string/titlecase.rb - lib/core/facets/string/to_re.rb - lib/core/facets/string/unbracket.rb - lib/core/facets/string/underscore.rb - lib/core/facets/string/unfold.rb - lib/core/facets/string/unindent.rb - lib/core/facets/string/unquote.rb - lib/core/facets/string/uppercase.rb - lib/core/facets/string/variablize.rb - lib/core/facets/string/word_wrap.rb - lib/core/facets/string/words.rb - lib/core/facets/string/xor.rb - lib/core/facets/string.rb - lib/core/facets/struct/attributes.rb - lib/core/facets/struct.rb - lib/core/facets/symbol/as_s.rb - lib/core/facets/symbol/bang.rb - lib/core/facets/symbol/chomp.rb - lib/core/facets/symbol/generate.rb - lib/core/facets/symbol/not.rb - lib/core/facets/symbol/op_div.rb - lib/core/facets/symbol/plain.rb - lib/core/facets/symbol/query.rb - lib/core/facets/symbol/reader.rb - lib/core/facets/symbol/setter.rb - lib/core/facets/symbol/succ.rb - lib/core/facets/symbol/thrown.rb - lib/core/facets/symbol/to_proc.rb - lib/core/facets/symbol/variablize.rb - lib/core/facets/symbol/writer.rb - lib/core/facets/symbol.rb - lib/core/facets/time/ago.rb - lib/core/facets/time/change.rb - lib/core/facets/time/dst_adjustment.rb - lib/core/facets/time/elapse.rb - lib/core/facets/time/future.rb - lib/core/facets/time/hence.rb - lib/core/facets/time/in.rb - lib/core/facets/time/less.rb - lib/core/facets/time/past.rb - lib/core/facets/time/round_to.rb - lib/core/facets/time/set.rb - lib/core/facets/time/shift.rb - lib/core/facets/time/stamp.rb - lib/core/facets/time/to_time.rb - lib/core/facets/time/trunc.rb - lib/core/facets/time.rb - lib/core/facets/to_hash.rb - lib/core/facets/unboundmethod/arguments.rb - lib/core/facets/unboundmethod/name.rb - lib/core/facets/unboundmethod.rb - lib/core/facets/version.rb - lib/core/facets.rb - lib/core/facets.yml - lib/standard/facets/argvector.rb - lib/standard/facets/basicobject.rb - lib/standard/facets/cgi.rb - lib/standard/facets/cloneable.rb - lib/standard/facets/continuation.rb - lib/standard/facets/date.rb - lib/standard/facets/digest/base64digest.rb - lib/standard/facets/digest/salted_digest.rb - lib/standard/facets/digest.rb - lib/standard/facets/enumargs.rb - lib/standard/facets/equitable.rb - lib/standard/facets/erb.rb - lib/standard/facets/fileutils/amass.rb - lib/standard/facets/fileutils/cp_rx.rb - lib/standard/facets/fileutils/head.rb - lib/standard/facets/fileutils/ln_r.rb - lib/standard/facets/fileutils/outofdate.rb - lib/standard/facets/fileutils/safe_ln.rb - lib/standard/facets/fileutils/slice.rb - lib/standard/facets/fileutils/stage.rb - lib/standard/facets/fileutils/tail.rb - lib/standard/facets/fileutils/wc.rb - lib/standard/facets/fileutils/whereis.rb - lib/standard/facets/fileutils/which.rb - lib/standard/facets/fileutils.rb - lib/standard/facets/find.rb - lib/standard/facets/getoptlong.rb - lib/standard/facets/instantiable.rb - lib/standard/facets/interval.rb - lib/standard/facets/math/abs.rb - lib/standard/facets/math/acot.rb - lib/standard/facets/math/acoth.rb - lib/standard/facets/math/acsc.rb - lib/standard/facets/math/acsch.rb - lib/standard/facets/math/amd.rb - lib/standard/facets/math/approx_equal.rb - lib/standard/facets/math/asec.rb - lib/standard/facets/math/asech.rb - lib/standard/facets/math/atkinson_index.rb - lib/standard/facets/math/beta.rb - lib/standard/facets/math/cdf.rb - lib/standard/facets/math/ceil.rb - lib/standard/facets/math/cot.rb - lib/standard/facets/math/coth.rb - lib/standard/facets/math/csc.rb - lib/standard/facets/math/csch.rb - lib/standard/facets/math/delta.rb - lib/standard/facets/math/epsilon.rb - lib/standard/facets/math/exp10.rb - lib/standard/facets/math/exp2.rb - lib/standard/facets/math/factorial.rb - lib/standard/facets/math/floor.rb - lib/standard/facets/math/gamma.rb - lib/standard/facets/math/gcd.rb - lib/standard/facets/math/gini_coefficient.rb - lib/standard/facets/math/kldivergence.rb - lib/standard/facets/math/lcm.rb - lib/standard/facets/math/lgamma.rb - lib/standard/facets/math/linsolve.rb - lib/standard/facets/math/log2.rb - lib/standard/facets/math/max.rb - lib/standard/facets/math/mean.rb - lib/standard/facets/math/median.rb - lib/standard/facets/math/min.rb - lib/standard/facets/math/percentile.rb - lib/standard/facets/math/pow.rb - lib/standard/facets/math/pstd.rb - lib/standard/facets/math/pvariance.rb - lib/standard/facets/math/rmd.rb - lib/standard/facets/math/root.rb - lib/standard/facets/math/round.rb - lib/standard/facets/math/sec.rb - lib/standard/facets/math/sech.rb - lib/standard/facets/math/sign.rb - lib/standard/facets/math/sinc.rb - lib/standard/facets/math/sqr.rb - lib/standard/facets/math/sqsolve.rb - lib/standard/facets/math/std.rb - lib/standard/facets/math/stderr.rb - lib/standard/facets/math/sum.rb - lib/standard/facets/math/summed_sqdevs.rb - lib/standard/facets/math/tgamma.rb - lib/standard/facets/math/theil_index.rb - lib/standard/facets/math/variance.rb - lib/standard/facets/math.rb - lib/standard/facets/memoizable.rb - lib/standard/facets/multipliers.rb - lib/standard/facets/multiton.rb - lib/standard/facets/net/http.rb - lib/standard/facets/nullclass.rb - lib/standard/facets/opesc.rb - lib/standard/facets/ostruct.rb - lib/standard/facets/pathname.rb - lib/standard/facets/platform.rb - lib/standard/facets/random.rb - lib/standard/facets/rbconfig.rb - lib/standard/facets/set.rb - lib/standard/facets/shellwords.rb - lib/standard/facets/strscan.rb - lib/standard/facets/thread.rb - lib/standard/facets/timer.rb - lib/standard/facets/tuple.rb - lib/standard/facets/uri.rb - lib/standard/facets/yaml.rb - lib/standard/facets/zlib.rb - qed/applique/file_helpers.rb - qed/core/array/combination.rdoc - qed/core/array/delete.rdoc - qed/core/array/index.rdoc - qed/core/array/merge.rdoc - qed/core/array/only.rdoc - qed/core/array/pad.rdoc - qed/core/array/permutation.rdoc - qed/core/array/product.rdoc - qed/core/array/recursively.rdoc - qed/core/array/rotate.rdoc - qed/core/array/select.rdoc - qed/core/array/uniq_by.rdoc - qed/core/binding/caller.rdoc - qed/core/binding/defined.rdoc - qed/core/binding/eval.rdoc - qed/core/binding/local_variables.rdoc - qed/core/binding/opvars.rdoc - qed/core/binding/self.rdoc - qed/core/class/descendants.rdoc - qed/core/class/to_proc.rdoc - qed/core/comparable/cap.rdoc - qed/core/comparable/clip.rdoc - qed/core/comparable/cmp.rdoc - qed/core/comparable/op_get.rdoc - qed/core/dir/ascend.rdoc - qed/core/dir/descend.rdoc - qed/core/dir/multiglob.rdoc - qed/core/dir/parent.rdoc - qed/core/dir/recurse.rdoc - qed/core/exception/detail.rdoc - qed/core/facets.rdoc - qed/core/filetest/root.rdoc - qed/core/hash/recursively.rdoc - qed/core/indexable.rdoc - qed/core/integer/bitmask.rdoc - qed/core/integer/even.rdoc - qed/core/integer/factorial.rdoc - qed/core/integer/length.rdoc - qed/core/integer/multiple.rdoc - qed/core/integer/odd.rdoc - qed/core/integer/of.rdoc - qed/core/integer/ordinal.rdoc - qed/core/matchdata/match.rdoc - qed/core/matchdata/matchset.rdoc - qed/core/module/cattr.rdoc - qed/core/module/class_extend.rdoc - qed/core/module/class_inheritor.rdoc - qed/core/module/copy_inheritor.rdoc - qed/core/module/method_space.rdoc - qed/core/string/align.rdoc - qed/core/string/bracket.rdoc - qed/core/string/bytes.rdoc - qed/core/string/camelcase.rdoc - qed/core/string/capitalized.rdoc - qed/core/string/characters.rdoc - qed/core/string/cleanlines.rdoc - qed/core/string/cleave.rdoc - qed/core/string/divide.rdoc - qed/core/string/each_char.rdoc - qed/core/string/each_word.rdoc - qed/core/string/end_with.rdoc - qed/core/string/expand_tabs.rdoc - qed/core/string/fold.rdoc - qed/core/string/indent.rdoc - qed/core/string/interpolate.rdoc - qed/core/string/lchomp.rdoc - qed/core/string/line_wrap.rdoc - qed/core/string/lines.rdoc - qed/core/string/margin.rdoc - qed/core/string/methodize.rdoc - qed/core/string/modulize.rdoc - qed/core/string/mscan.rdoc - qed/core/string/natcmp.rdoc - qed/core/string/nchar.rdoc - qed/core/string/newlines.rdoc - qed/core/string/op_sub.rdoc - qed/core/string/pathize.rdoc - qed/core/string/quote.rdoc - qed/core/string/range.rdoc - qed/core/string/rewrite.rdoc - qed/core/string/shatter.rdoc - qed/core/string/snakecase.rdoc - qed/core/string/splice.rdoc - qed/core/string/start_with.rdoc - qed/core/string/subtract.rdoc - qed/core/string/tab.rdoc - qed/core/string/tabto.rdoc - qed/core/string/titlecase.rdoc - qed/core/string/to_re.rdoc - qed/core/string/unfold.rdoc - qed/core/string/unindent.rdoc - qed/core/string/unquote.rdoc - qed/core/string/variablize.rdoc - qed/core/string/word_wrap.rdoc - qed/core/string/words.rdoc - qed/core/string/xor.rdoc - qed/standard/02_cloneable.rdoc - qed/standard/03_enumargs.rdoc - qed/standard/04_equitable.rdoc - qed/standard/05_instantiable.rdoc - qed/standard/basic_object.rdoc - qed/standard/memoizable.rdoc - qed/standard/mulititon.rdoc - test/core/array/test_after.rb - test/core/array/test_before.rb - test/core/array/test_collapse.rb - test/core/array/test_combination.rb - test/core/array/test_commonality.rb - test/core/array/test_conjoin.rb - test/core/array/test_contains.rb - test/core/array/test_delete.rb - test/core/array/test_divide.rb - test/core/array/test_duplicates.rb - test/core/array/test_entropy.rb - test/core/array/test_extract_options.rb - test/core/array/test_first.rb - test/core/array/test_index.rb - test/core/array/test_last.rb - test/core/array/test_median.rb - test/core/array/test_merge.rb - test/core/array/test_mode.rb - test/core/array/test_nonuniq.rb - test/core/array/test_not_empty.rb - test/core/array/test_occurent.rb - test/core/array/test_only.rb - test/core/array/test_pad.rb - test/core/array/test_peek.rb - test/core/array/test_permutation.rb - test/core/array/test_poke.rb - test/core/array/test_probability.rb - test/core/array/test_product.rb - test/core/array/test_pull.rb - test/core/array/test_recurse.rb - test/core/array/test_recursively.rb - test/core/array/test_rotate.rb - test/core/array/test_select.rb - test/core/array/test_splice.rb - test/core/array/test_split.rb - test/core/array/test_store.rb - test/core/array/test_traverse.rb - test/core/array/test_uniq_by.rb - test/core/binding/test_caller.rb - test/core/binding/test_defined.rb - test/core/binding/test_eval.rb - test/core/binding/test_local_variables.rb - test/core/binding/test_op.rb - test/core/binding/test_self.rb - test/core/class/test_descendents.rb - test/core/class/test_preallocate.rb - test/core/class/test_subclasses.rb - test/core/class/test_to_proc.rb - test/core/comparable/test_bound.rb - test/core/comparable/test_cap.rb - test/core/comparable/test_clip.rb - test/core/comparable/test_cmp.rb - test/core/comparable/test_op_get.rb - test/core/denumerable_tc.rb - test/core/dir/test_ascend.rb - test/core/dir/test_descend.rb - test/core/dir/test_each_child.rb - test/core/dir/test_multiglob.rb - test/core/dir/test_parent.rb - test/core/dir/test_recurse.rb - test/core/enumerable/test_accumulate.rb - test/core/enumerable/test_cluster_by.rb - test/core/enumerable/test_compact_map.rb - test/core/enumerable/test_count.rb - test/core/enumerable/test_defer.rb - test/core/enumerable/test_each_by.rb - test/core/enumerable/test_each_with_object.rb - test/core/enumerable/test_every.rb - test/core/enumerable/test_ewise.rb - test/core/enumerable/test_exclude.rb - test/core/enumerable/test_expand.rb - test/core/enumerable/test_filter.rb - test/core/enumerable/test_find_yield.rb - test/core/enumerable/test_frequency.rb - test/core/enumerable/test_graph.rb - test/core/enumerable/test_group_by.rb - test/core/enumerable/test_map_by.rb - test/core/enumerable/test_map_send.rb - test/core/enumerable/test_map_with_index.rb - test/core/enumerable/test_mash.rb - test/core/enumerable/test_modulate.rb - test/core/enumerable/test_none.rb - test/core/enumerable/test_occur.rb - test/core/enumerable/test_one.rb - test/core/enumerable/test_per.rb - test/core/enumerable/test_purge.rb - test/core/enumerable/test_recursively.rb - test/core/enumerable/test_sum.rb - test/core/enumerable/test_take.rb - test/core/enumerable/test_uniq_by.rb - test/core/enumerable/test_visit.rb - test/core/enumerator/test_fx.rb - test/core/enumerator/test_new.rb - test/core/enumerator_tc.rb - test/core/exception/test_detail.rb - test/core/exception/test_raised.rb - test/core/exception/test_suppress.rb - test/core/file/test_append.rb - test/core/file/test_create.rb - test/core/file/test_ext.rb - test/core/file/test_null.rb - test/core/file/test_read_binary.rb - test/core/file/test_read_list.rb - test/core/file/test_rewrite.rb - test/core/file/test_rootname.rb - test/core/file/test_sanitize.rb - test/core/file/test_split_all.rb - test/core/file/test_write.rb - test/core/file/test_writelines.rb - test/core/filetest/test_root.rb - test/core/functor_tc.rb - test/core/hash/test_alias.rb - test/core/hash/test_argumentize.rb - test/core/hash/test_at.rb - test/core/hash/test_autonew.rb - test/core/hash/test_collate.rb - test/core/hash/test_count.rb - test/core/hash/test_data.rb - test/core/hash/test_dearray_values.rb - test/core/hash/test_deep_merge.rb - test/core/hash/test_delete_at.rb - test/core/hash/test_delete_unless.rb - test/core/hash/test_delete_values.rb - test/core/hash/test_diff.rb - test/core/hash/test_expect.rb - test/core/hash/test_graph.rb - test/core/hash/test_insert.rb - test/core/hash/test_inverse.rb - test/core/hash/test_join.rb - test/core/hash/test_keys.rb - test/core/hash/test_new_with.rb - test/core/hash/test_op_add.rb - test/core/hash/test_op_and.rb - test/core/hash/test_op_mul.rb - test/core/hash/test_op_or.rb - test/core/hash/test_op_push.rb - test/core/hash/test_op_sub.rb - test/core/hash/test_recurse.rb - test/core/hash/test_recursively.rb - test/core/hash/test_rekey.rb - test/core/hash/test_replace_each.rb - test/core/hash/test_reverse_merge.rb - test/core/hash/test_select.rb - test/core/hash/test_slice.rb - test/core/hash/test_stringify_keys.rb - test/core/hash/test_swap.rb - test/core/hash/test_symbolize_keys.rb - test/core/hash/test_to_mod.rb - test/core/hash/test_to_proc.rb - test/core/hash/test_to_struct.rb - test/core/hash/test_traverse.rb - test/core/hash/test_update_each.rb - test/core/hash/test_update_keys.rb - test/core/hash/test_update_values.rb - test/core/hash/test_url_params.rb - test/core/hash/test_weave.rb - test/core/hash/test_zip.rb - test/core/indexable_tc.rb - test/core/integer/test_bitmask.rb - test/core/integer/test_even.rb - test/core/integer/test_factorial.rb - test/core/integer/test_multiple.rb - test/core/integer/test_odd.rb - test/core/integer/test_of.rb - test/core/integer/test_ordinal.rb - test/core/kernel/test_as.rb - test/core/kernel/test_ask.rb - test/core/kernel/test_assign.rb - test/core/kernel/test_assign_from.rb - test/core/kernel/test_attr_singleton.rb - test/core/kernel/test_blank.rb - test/core/kernel/test_callstack.rb - test/core/kernel/test_class.rb - test/core/kernel/test_complete.rb - test/core/kernel/test_constant.rb - test/core/kernel/test_d.rb - test/core/kernel/test_deep_copy.rb - test/core/kernel/test_dir.rb - test/core/kernel/test_disable_warnings.rb - test/core/kernel/test_ergo.rb - test/core/kernel/test_extension.rb - test/core/kernel/test_get.rb - test/core/kernel/test_here.rb - test/core/kernel/test_hierarchical_send.rb - test/core/kernel/test_in.rb - test/core/kernel/test_instance_assign.rb - test/core/kernel/test_instance_class.rb - test/core/kernel/test_instance_send.rb - test/core/kernel/test_maybe.rb - test/core/kernel/test_meta_alias.rb - test/core/kernel/test_meta_class.rb - test/core/kernel/test_meta_def.rb - test/core/kernel/test_meta_eval.rb - test/core/kernel/test_method.rb - test/core/kernel/test_not.rb - test/core/kernel/test_not_nil.rb - test/core/kernel/test_object_class.rb - test/core/kernel/test_object_hexid.rb - test/core/kernel/test_object_send.rb - test/core/kernel/test_presence.rb - test/core/kernel/test_qua_class.rb - test/core/kernel/test_require_all.rb - test/core/kernel/test_require_relative.rb - test/core/kernel/test_respond.rb - test/core/kernel/test_returning.rb - test/core/kernel/test_silence.rb - test/core/kernel/test_singleton_class.rb - test/core/kernel/test_source_location.rb - test/core/kernel/test_super_method.rb - test/core/kernel/test_tap.rb - test/core/kernel/test_temporarily.rb - test/core/kernel/test_true.rb - test/core/kernel/test_try.rb - test/core/kernel/test_val.rb - test/core/kernel/test_with.rb - test/core/kernel/test_writers.rb - test/core/matchdata/test_match.rb - test/core/matchdata/test_matchset.rb - test/core/module/test_abstract.rb - test/core/module/test_alias_accessor.rb - test/core/module/test_alias_method_chain.rb - test/core/module/test_alias_module_function.rb - test/core/module/test_all_instance_methods.rb - test/core/module/test_ancestor.rb - test/core/module/test_anonymous.rb - test/core/module/test_attr_setter.rb - test/core/module/test_basename.rb - test/core/module/test_can.rb - test/core/module/test_class.rb - test/core/module/test_class_def.rb - test/core/module/test_class_extend.rb - test/core/module/test_class_inheritor.rb - test/core/module/test_copy_inheritor.rb - test/core/module/test_enclosure.rb - test/core/module/test_instance_function.rb - test/core/module/test_instance_method.rb - test/core/module/test_instance_method_defined.rb - test/core/module/test_integrate.rb - test/core/module/test_is.rb - test/core/module/test_memoize.rb - test/core/module/test_method_clash.rb - test/core/module/test_method_space.rb - test/core/module/test_methodize.rb - test/core/module/test_modname.rb - test/core/module/test_module_def.rb - test/core/module/test_module_load.rb - test/core/module/test_nodef.rb - test/core/module/test_op.rb - test/core/module/test_pathize.rb - test/core/module/test_preextend.rb - test/core/module/test_redefine_method.rb - test/core/module/test_redirect_method.rb - test/core/module/test_remove.rb - test/core/module/test_rename_method.rb - test/core/module/test_revise.rb - test/core/module/test_set.rb - test/core/module/test_spacename.rb - test/core/module/test_to_obj.rb - test/core/module/test_wrap_method.rb - test/core/nilclass/test_to_f.rb - test/core/numeric/test_approx.rb - test/core/numeric/test_distance.rb - test/core/numeric/test_length.rb - test/core/numeric/test_round.rb - test/core/numeric/test_spacing.rb - test/core/object/test_dup.rb - test/core/object/test_object_state.rb - test/core/object/test_replace.rb - test/core/object/test_try_dup.rb - test/core/proc/test_bind.rb - test/core/proc/test_bind_to.rb - test/core/proc/test_compose.rb - test/core/proc/test_curry.rb - test/core/proc/test_partial.rb - test/core/proc/test_to_method.rb - test/core/proc/test_update.rb - test/core/range/test_combine.rb - test/core/range/test_overlap.rb - test/core/range/test_to_r.rb - test/core/range/test_umbrella.rb - test/core/range/test_within.rb - test/core/regexp/test_arity.rb - test/core/regexp/test_multiline.rb - test/core/regexp/test_op_add.rb - test/core/regexp/test_op_or.rb - test/core/regexp/test_to_re.rb - test/core/string/test_align.rb - test/core/string/test_bracket.rb - test/core/string/test_bytes.rb - test/core/string/test_camelcase.rb - test/core/string/test_capitalized.rb - test/core/string/test_characters.rb - test/core/string/test_cleanlines.rb - test/core/string/test_cleave.rb - test/core/string/test_cmp.rb - test/core/string/test_compress_lines.rb - test/core/string/test_divide.rb - test/core/string/test_each_char.rb - test/core/string/test_each_word.rb - test/core/string/test_edit_distance.rb - test/core/string/test_end_with.rb - test/core/string/test_exclude.rb - test/core/string/test_expand_tabs.rb - test/core/string/test_file.rb - test/core/string/test_fold.rb - test/core/string/test_indent.rb - test/core/string/test_index_all.rb - test/core/string/test_interpolate.rb - test/core/string/test_lchomp.rb - test/core/string/test_line_wrap.rb - test/core/string/test_lines.rb - test/core/string/test_lowercase.rb - test/core/string/test_margin.rb - test/core/string/test_methodize.rb - test/core/string/test_modulize.rb - test/core/string/test_mscan.rb - test/core/string/test_natcmp.rb - test/core/string/test_nchar.rb - test/core/string/test_newlines.rb - test/core/string/test_op_div.rb - test/core/string/test_op_sub.rb - test/core/string/test_pathize.rb - test/core/string/test_quote.rb - test/core/string/test_range.rb - test/core/string/test_rewrite.rb - test/core/string/test_shatter.rb - test/core/string/test_similarity.rb - test/core/string/test_snakecase.rb - test/core/string/test_splice.rb - test/core/string/test_squish.rb - test/core/string/test_start_with.rb - test/core/string/test_store.rb - test/core/string/test_subtract.rb - test/core/string/test_tab.rb - test/core/string/test_tabto.rb - test/core/string/test_titlecase.rb - test/core/string/test_to_re.rb - test/core/string/test_unbracket.rb - test/core/string/test_underscore.rb - test/core/string/test_unfold.rb - test/core/string/test_unindent.rb - test/core/string/test_unquote.rb - test/core/string/test_uppercase.rb - test/core/string/test_variablize.rb - test/core/string/test_word_wrap.rb - test/core/string/test_words.rb - test/core/string/test_xor.rb - test/core/symbol/test_as_s.rb - test/core/symbol/test_bang.rb - test/core/symbol/test_chomp.rb - test/core/symbol/test_generate.rb - test/core/symbol/test_not.rb - test/core/symbol/test_op_div.rb - test/core/symbol/test_plain.rb - test/core/symbol/test_query.rb - test/core/symbol/test_setter.rb - test/core/symbol/test_succ.rb - test/core/symbol/test_to_proc.rb - test/core/symbol/test_variablize.rb - test/core/time/test_ago.rb - test/core/time/test_change.rb - test/core/time/test_dst_adjustment.rb - test/core/time/test_elapse.rb - test/core/time/test_future.rb - test/core/time/test_hence.rb - test/core/time/test_in.rb - test/core/time/test_less.rb - test/core/time/test_past.rb - test/core/time/test_round_to.rb - test/core/time/test_set.rb - test/core/time/test_shift.rb - test/core/time/test_stamp.rb - test/core/time/test_to_time.rb - test/core/time/test_trunc.rb - test/core/to_hash_tc.rb - test/core/unboundmethod/test_arguments.rb - test/core/unboundmethod/test_name.rb - test/standard/math/test_abs.rb - test/standard/math/test_median.rb - test/standard/math/test_percentile.rb - test/standard/math/test_sign.rb - test/standard/test_argvector.rb - test/standard/test_cloneable.rb - test/standard/test_date.rb - test/standard/test_enumargs.rb - test/standard/test_equitable.rb - test/standard/test_instantiable.rb - test/standard/test_memoizable.rb - test/standard/test_multipliers.rb - test/standard/test_ostruct.rb - test/standard/test_random.rb - test/standard/test_shellwords.rb - test/standard/test_thread.rb - test/standard/test_timer.rb - test/standard/test_tuple.rb - test/standard/test_uri.rb - HISTORY.rdoc - README.rdoc - RUBY.txt - NOTICE.rdoc homepage: http://rubyworks.github.com/facets licenses: - Ruby post_install_message: rdoc_options: [] require_paths: - lib/core - lib/standard required_ruby_version: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' required_rubygems_version: !ruby/object:Gem::Requirement none: false requirements: - - ! '>=' - !ruby/object:Gem::Version version: '0' requirements: [] rubyforge_project: rubygems_version: 1.8.10 signing_key: specification_version: 3 summary: Premium Ruby Extensions test_files: [] facets-2.9.3/.yardopts0000644000004100000410000000022211714455226014673 0ustar www-datawww-data--title "Ruby Facets" --readme README.rdoc --protected --private --tag uncommon:Uncommon --tag standard:Standard lib/core lib/standard - [A-Z]*.* facets-2.9.3/.ruby0000644000004100000410000000241111714455226014011 0ustar www-datawww-data--- source: - var authors: - name: Thomas Sawyer email: transfire@gmail.com copyrights: - holder: Thomas Sawyer year: '2004' license: Ruby replacements: [] alternatives: [] requirements: - name: lemon groups: - test development: true - name: qed groups: - test development: true - name: detroit groups: - build development: true dependencies: [] conflicts: [] repositories: - uri: git@github.com:rubyworks/facets.git scm: git name: upstream resources: home: http://rubyworks.github.com/facets code: http://github.com/rubyworks/facets docs: http://rubyworks.github.com/facets/learn.html wiki: http://wiki.github.com/rubyworks/facets talk: http://groups.google.com/group/facets-universal extra: {} load_path: - lib/core - lib/standard revision: 0 created: '2004-12-16' summary: Premium Ruby Extensions title: Facets version: 2.9.3 name: facets description: Facets is the premier collection of extension methods for the Ruby programming language. Facets extensions are unique by virtue of thier atomicity. They are stored in individual files allowing for highly granular control of requirements. In addition, Facets includes a few additional classes and mixins suitable to wide variety of applications. organization: rubyworks date: '2011-12-31' facets-2.9.3/qed/0000755000004100000410000000000011714455226013602 5ustar www-datawww-datafacets-2.9.3/qed/core/0000755000004100000410000000000011714455226014532 5ustar www-datawww-datafacets-2.9.3/qed/core/comparable/0000755000004100000410000000000011714455226016637 5ustar www-datawww-datafacets-2.9.3/qed/core/comparable/clip.rdoc0000644000004100000410000000124411714455226020440 0ustar www-datawww-data== Comparable#clip require 'facets/comparable/clip' single argument 3.clip(4).assert == 4 4.clip(4).assert == 4 5.clip(4).assert == 5 two arguments 4.clip(3,5).assert == 4 3.clip(3,5).assert == 3 5.clip(3,5).assert == 5 2.clip(3,5).assert == 3 6.clip(3,5).assert == 5 on strings 'd'.clip('c','e').assert == 'd' 'c'.clip('c','e').assert == 'c' 'e'.clip('c','e').assert == 'e' 'b'.clip('c','e').assert == 'c' 'f'.clip('c','e').assert == 'e' == Comparable#bound The bound method is an alias for #clip. It is actually the original name of this method. 3.bound(4).assert == 4 4.bound(3,5).assert == 4 'd'.bound('c','e').assert == 'd' facets-2.9.3/qed/core/comparable/op_get.rdoc0000644000004100000410000000074411714455226020772 0ustar www-datawww-data== Comparable#[] require 'facets/comparable/op_get' c = Class.new do include Comparable[:a,:b] attr_accessor :a, :b def initialize(a,b) @a=a; @b=b end end a = [c.new(10,20),c.new(10,30)] a.sort.assert == a a = [c.new(10,30),c.new(10,20)] a.sort.assert == a.reverse a = [c.new(10,10),c.new(20,10)] a.sort.assert == a a = [c.new(20,10),c.new(10,10)] a.sort.assert == a.reverse a = [c.new(10,30),c.new(20,10)] a.sort.assert == a facets-2.9.3/qed/core/comparable/cmp.rdoc0000644000004100000410000000047211714455226020272 0ustar www-datawww-data== Comparable#cmp require 'facets/comparable/cmp' on integers 3.cmp(4).assert == -1 3.cmp(3).assert == 0 3.cmp(2).assert == 1 on strings "abc".cmp("abc").assert == 0 "abc".cmp("abcd").assert == -1 "abcd".cmp("abc").assert == 1 "abc".cmp("bcd").assert == -1 "bcd".cmp("abc").assert == 1 facets-2.9.3/qed/core/comparable/cap.rdoc0000644000004100000410000000052211714455226020252 0ustar www-datawww-data== Comparable#cap require 'facets/comparable/cap' 3.cap(4).assert == 3 4.cap(4).assert == 4 5.cap(4).assert == 4 == Comparable#at_most 3.at_most(4).assert == 3 4.at_most(4).assert == 4 5.at_most(4).assert == 4 == Comparable#at_least 3.at_least(4).assert == 4 4.at_least(4).assert == 4 5.at_least(4).assert == 5 facets-2.9.3/qed/core/filetest/0000755000004100000410000000000011714455226016351 5ustar www-datawww-datafacets-2.9.3/qed/core/filetest/root.rdoc0000644000004100000410000000012311714455226020201 0ustar www-datawww-data== FileTest#root? require 'facets/filetest/root' FileTest.assert.root?('/') facets-2.9.3/qed/core/array/0000755000004100000410000000000011714455226015650 5ustar www-datawww-datafacets-2.9.3/qed/core/array/index.rdoc0000644000004100000410000000030411714455226017625 0ustar www-datawww-data== Array#index require 'facets/array/index' can handle a block i = [1,2,3].index{ |e| e == 2 } i.assert == 1 when no element is found i = [1,2,3].index{ |e| e == 5 } i.assert.nil? facets-2.9.3/qed/core/array/only.rdoc0000644000004100000410000000024611714455226017504 0ustar www-datawww-data== Array#only require 'facets/array/only' [5].only.assert == 5 [nil].only.assert == nil expect(IndexError){ [].only } expect(IndexError){ [1,2,3].only } facets-2.9.3/qed/core/array/pad.rdoc0000644000004100000410000000060711714455226017270 0ustar www-datawww-data== Array#pad require 'facets/array/pad' r = [0,1,2,3].pad(7,"x") x = [0,1,2,3,"x","x","x"] r.assert == x negative index r = [0,1,2,3].pad(-7,"n") x = ["n","n","n",0,1,2,3] r.assert == x == Array#pad! a = [0,1,2,3] r = a.pad!(6,"y") x = [0,1,2,3,"y","y"] r.assert == x negative index a = [0,1,2,3] r = a.pad!(-6,"q") x = ["q","q",0,1,2,3] r.assert == x facets-2.9.3/qed/core/array/product.rdoc0000644000004100000410000000075211714455226020205 0ustar www-datawww-data== Array#product require 'facets/array/product' single argument r = [1,2,3].product([4,5,6]) x = [[1, 4],[1, 5],[1, 6],[2, 4],[2, 5],[2, 6],[3, 4],[3, 5],[3, 6]] r.assert == x multiple arguments a = %w|a b| b = %w|a x| c = %w|x y| r = a.product(b, c) x = [ ["a", "a", "x"], ["a", "a", "y"], ["a", "x", "x"], ["a", "x", "y"], ["b", "a", "x"], ["b", "a", "y"], ["b", "x", "x"], ["b", "x", "y"] ] r.assert == x facets-2.9.3/qed/core/array/merge.rdoc0000644000004100000410000000030611714455226017617 0ustar www-datawww-data== Array#merge require 'facets/array/merge' a = [1,2,3] b = [3,4,5] a.merge(b).assert == [1,2,3,4,5] == Array#merge! a = [1,2,3] b = [3,4,5] a.merge!(b) a.assert == [1,2,3,4,5] facets-2.9.3/qed/core/array/uniq_by.rdoc0000644000004100000410000000021711714455226020167 0ustar www-datawww-data== Array#uniq_by! require 'facets/array/uniq_by' e = [-5, -4, -3, -2, -1, 0] r = (-5..5).to_a r.uniq_by!{ |i| i*i } r.assert == e facets-2.9.3/qed/core/array/recursively.rdoc0000644000004100000410000000036011714455226021074 0ustar www-datawww-data== Array#recursive require 'facets/array/recursively' each r = [] [1,2,['a','b']].recursively.each{ |v| r << v } r.assert == [1,2,'a','b'] map r = [1,2,['a','b']].recursively.map{ |v| v.succ } r.assert == [2,3,['b','c']] facets-2.9.3/qed/core/array/combination.rdoc0000644000004100000410000000054111714455226021023 0ustar www-datawww-data== Array#combination require 'facets/array/combination' finds pairs of combinations e = [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]] a = [1,2,3,4] r = a.combination(2).to_a r.assert == e can also take a block e = [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] r = [] a = [1,2,3,4] a.combination(2){ |a,b| r << [a,b] } r.assert == e facets-2.9.3/qed/core/array/delete.rdoc0000644000004100000410000000062711714455226017770 0ustar www-datawww-data== Array#delete_unless require 'facets/array/delete' a = [1,2,3] a.delete_unless{ |e| e == 2 } a.assert == [2] == Array#delete_values a = [1,2,3,4] a.delete_values(1,2).assert == [1,2] a.assert == [3,4] == Array#delete_values_at a = [1,2,3,4] a.delete_values_at(1,2).assert == [2,3] a.assert == [1,4] a = [1,2,3,4] a.delete_values_at(0..2).assert == [1,2,3] a.assert == [4] facets-2.9.3/qed/core/array/rotate.rdoc0000644000004100000410000000052211714455226020016 0ustar www-datawww-data== Array#rotate require 'facets/array/rotate' clockwise a = [1,2,3] r = a.rotate r.assert == [2,3,1] counter-clockwise a = [1,2,3] r = a.rotate(-1) r.assert == [3,1,2] == Array#rotate! clockwise a = [1,2,3] a.rotate! a.assert == [2,3,1] counter-clockwise a = [1,2,3] a.rotate!(-1) a.assert == [3,1,2] facets-2.9.3/qed/core/array/select.rdoc0000644000004100000410000000021111714455226017772 0ustar www-datawww-data== Array#select require 'facets/array/select' a = [1,2,3,4,5,6,7,8,9,10] a.select!{ |e| e % 2 == 0 } a.assert == [2,4,6,8,10] facets-2.9.3/qed/core/array/permutation.rdoc0000644000004100000410000000031711714455226021071 0ustar www-datawww-data== Array#permutation require 'facets/array/permutation' require 'set' r = Set.new %w[a b c].permutation{ |x| r << x.join('') } x = Set.new(['abc','acb','bac','bca','cab','cba']) r.assert == x facets-2.9.3/qed/core/matchdata/0000755000004100000410000000000011714455226016460 5ustar www-datawww-datafacets-2.9.3/qed/core/matchdata/matchset.rdoc0000644000004100000410000000066511714455226021150 0ustar www-datawww-data== MatchData#matchtree require 'facets/matchdata/matchset' md = /(bb)(cc(dd))(ee)/.match "XXaabbccddeeffXX" md.matchtree.assert == [["bb"], ["cc", ["dd"]], ["ee"]] md = /(bb)c(c(dd))(ee)/.match "XXaabbccddeeffXX" md.matchtree.assert == [["bb"], "c", ["c", ["dd"]], ["ee"]] == MatchData#matchset md = /(bb)(cc(dd))(ee)/.match "XXaabbccddeeffXX" md.matchset.assert == ["XXaa", [["bb"], ["cc", ["dd"]], ["ee"]], "ffXX"] facets-2.9.3/qed/core/matchdata/match.rdoc0000644000004100000410000000017311714455226020426 0ustar www-datawww-data= MatchData#match require 'facets/matchdata/match' md = /X(a)(b)(c)X/.match("YXabcXY") md.match.assert == "XabcX" facets-2.9.3/qed/core/exception/0000755000004100000410000000000011714455226016530 5ustar www-datawww-datafacets-2.9.3/qed/core/exception/detail.rdoc0000644000004100000410000000025511714455226020645 0ustar www-datawww-data== Exception#detail require 'facets/exception/detail' begin raise ArgumentError rescue ArgumentError => err e = r = err.detail r.assert == e end facets-2.9.3/qed/core/integer/0000755000004100000410000000000011714455226016167 5ustar www-datawww-datafacets-2.9.3/qed/core/integer/multiple.rdoc0000644000004100000410000000026511714455226020676 0ustar www-datawww-data== Integer#multiple? require 'facets/integer/multiple' 1.multiple?(2) #=> false 5.multiple?(3) #=> false 2.multiple?(2) #=> true 6.multiple?(3) #=> true facets-2.9.3/qed/core/integer/odd.rdoc0000644000004100000410000000027411714455226017611 0ustar www-datawww-data== Integer#odd? require 'facets/integer/odd' (-101..101).step(2) do |n| n.odd?.assert == true end (-100..100).step(2) do |n| n.odd?.assert == false end facets-2.9.3/qed/core/integer/bitmask.rdoc0000644000004100000410000000127211714455226020474 0ustar www-datawww-data== Integer#bit require 'facets/integer/bitmask' 0.bit(0).assert == 1 0.bit(1).assert == 2 0.bit(2).assert == 4 0.bit(3).assert == 8 negate 1.bit(~0).assert == 0 2.bit(~1).assert == 0 4.bit(~2).assert == 0 8.bit(~3).assert == 0 == Integer#bit? a = 8 assert(! a.bit?(0)) assert(! a.bit?(1)) assert(! a.bit?(2)) assert( a.bit?(3)) assert(! a.bit?(4)) assert(! a.bit?(5)) == Integer#bit_clear 1.bit_clear(0).assert == 0 2.bit_clear(1).assert == 0 4.bit_clear(2).assert == 0 8.bit_clear(3).assert == 0 == Integer#bitmask a = 1 m = Bit(4) a = a.bitmask(m) a.assert == 17 assert( a.bitmask?(m) ) == Kernel#Bit n = Bit(4) n.assert == 16 facets-2.9.3/qed/core/integer/even.rdoc0000644000004100000410000000030011714455226017766 0ustar www-datawww-data== Integer#even? require 'facets/integer/even' (-100..100).step(2) do |n| n.even?.assert == true end (-101..101).step(2) do |n| n.even?.assert == false end facets-2.9.3/qed/core/integer/of.rdoc0000644000004100000410000000031711714455226017445 0ustar www-datawww-data== Integer#of require 'facets/integer/of' a = 4 b = a.of{ |i| i*2 } b.assert == [0,2,4,6] == Integer#times_collect a = 4 b = a.times_collect{ |i| i*2 } b.assert == [0,2,4,6] facets-2.9.3/qed/core/integer/ordinal.rdoc0000644000004100000410000000026211714455226020470 0ustar www-datawww-data= Integer#ordinal require 'facets/integer/ordinal' 1.ordinal.assert == '1st' 2.ordinal.assert == '2nd' 3.ordinal.assert == '3rd' 4.ordinal.assert == '4th' facets-2.9.3/qed/core/integer/factorial.rdoc0000644000004100000410000000031411714455226021002 0ustar www-datawww-data== Integer#factorial require 'facets/integer/factorial' 0.factorial.assert == 1 1.factorial.assert == 1 2.factorial.assert == 2 3.factorial.assert == 6 4.factorial.assert == 24 facets-2.9.3/qed/core/integer/length.rdoc0000644000004100000410000000016111714455226020317 0ustar www-datawww-data== Numeric#length require 'facets/numeric/length' 10.length.assert == 10 10.0.length.assert == 10 facets-2.9.3/qed/core/binding/0000755000004100000410000000000011714455226016144 5ustar www-datawww-datafacets-2.9.3/qed/core/binding/self.rdoc0000644000004100000410000000011211714455226017740 0ustar www-datawww-data== Binding#self require 'facets/binding/self' binding.self == self facets-2.9.3/qed/core/binding/eval.rdoc0000644000004100000410000000015011714455226017740 0ustar www-datawww-data== Binding#eval require 'facets/binding/eval' x = "hello" binding.eval("x").assert == "hello" facets-2.9.3/qed/core/binding/caller.rdoc0000644000004100000410000000175011714455226020262 0ustar www-datawww-dataThe caller.rb script includes a few related methods. We will use the following code to demonstrate their use. require 'facets/binding/caller' a = 1 b = 2 x = "hello" @bind = binding @line = __LINE__ # the line number must be updated if it moves @file = __FILE__ # why does it equal basename only? == Binding#caller @bind.caller == Binding#callstack @bind.callstack.assert.is_a?(Array) == Binding#__LINE__ @bind.__LINE__.assert == @line - 1 == Binding#__FILE__ @bind.__FILE__.assert == @file == Binding#__DIR__ @bind.__DIR__.assert == File.dirname(@file) == Binding#__callee__ This only works for certain versions. def alternate_callee binding end unless RUBY_VERSION < "1.9" alternate_callee.__callee__.assert == :alternate_callee end == Binding#__method__ This only works for certain versions. def alternate_method binding end unless RUBY_VERSION < "1.8.7" alternate_method.__method__.assert == :alternate_method end facets-2.9.3/qed/core/binding/opvars.rdoc0000644000004100000410000000027711714455226020335 0ustar www-datawww-data== Binding#[] require 'facets/binding/op' a = 1 b = 2 x = "hello" binding["x"].assert == "hello" == Binding#[]= binding["x"] = "goodbye" binding["x"].assert == "goodbye" facets-2.9.3/qed/core/binding/defined.rdoc0000644000004100000410000000017011714455226020411 0ustar www-datawww-data== Binding#defined? require 'facets/binding/defined' a = 1 b = 2 x = "hello" binding.assert.defined?("x") facets-2.9.3/qed/core/binding/local_variables.rdoc0000644000004100000410000000063011714455226022136 0ustar www-datawww-data== Binding#local_variables require 'facets/binding/local_variables' a = 1 b = 2 x = "hello" unless RUBY_VERSION > "1.9" lvars = binding.local_variables lvars.assert.include?('a') lvars.assert.include?('b') lvars.assert.include?('x') else lvars = binding.local_variables lvars.assert.include?(:a) lvars.assert.include?(:b) lvars.assert.include?(:x) end facets-2.9.3/qed/core/facets.rdoc0000644000004100000410000000016211714455226016647 0ustar www-datawww-data= Requiring Facets We should be able to require all the core libraries by simply calling, require 'facets' facets-2.9.3/qed/core/class/0000755000004100000410000000000011714455226015637 5ustar www-datawww-datafacets-2.9.3/qed/core/class/descendants.rdoc0000644000004100000410000000022411714455226021001 0ustar www-datawww-data== Class#descendants require 'facets/class/descendants' a = Class.new b = Class.new(a) c = Class.new(b) a.descendants.assert == [b,c] facets-2.9.3/qed/core/class/to_proc.rdoc0000644000004100000410000000022311714455226020152 0ustar www-datawww-data== Class#to_proc require 'facets/class/to_proc' person = Struct.new(:name) people = ["joe"].map(&person) people[0].name.assert == "joe" facets-2.9.3/qed/core/string/0000755000004100000410000000000011714455226016040 5ustar www-datawww-datafacets-2.9.3/qed/core/string/words.rdoc0000644000004100000410000000035011714455226020045 0ustar www-datawww-data== String#words require 'facets/string/words' x = "a b c\nd e" x.words.assert == ['a','b','c','d','e'] x = "ab cd\nef" x.words.assert == ['ab','cd','ef'] x = "ab cd \n ef-gh" x.words.assert == ['ab','cd','ef-gh'] facets-2.9.3/qed/core/string/each_word.rdoc0000644000004100000410000000024111714455226020641 0ustar www-datawww-data== String#each_word require 'facets/string/each_word' a = [] i = "this is a test" i.each_word{ |w| a << w } a.assert == ['this', 'is', 'a', 'test'] facets-2.9.3/qed/core/string/tabto.rdoc0000644000004100000410000000125311714455226020023 0ustar www-datawww-data== String#tabto require 'facets/string/tabto' String#tabto indeent lines relative to their current indentions. Using #tabto on a single line behaves just like #tab. a = "xyz".tabto(2) a.assert == " xyz" a = " xyz".tabto(2) a.assert == " xyz" If the string has multiple lines, then each line will be indented accordingly. a = "abc\nxyz".tabto(2) a.assert == " abc\n xyz" Unlike #tab, the left margin of indention is determined by the first non-blank line. a = " abc\n xyz".tabto(2) a.assert == " abc\n xyz" If we add a blank line at the begining it will be the same. a = " \n abc\n xyz".tabto(2) a.assert == " \n abc\n xyz" facets-2.9.3/qed/core/string/interpolate.rdoc0000644000004100000410000000020411714455226021233 0ustar www-datawww-data== String#interpolate require 'facets/string/interpolate' a = 1 String.interpolate{ 'this is #{a}' }.assert == 'this is 1' facets-2.9.3/qed/core/string/fold.rdoc0000644000004100000410000000061011714455226017632 0ustar www-datawww-data== String#fold require 'facets/string/fold' s = "This is\na test.\n\nIt clumps\nlines of text." o = "This is a test.\n\nIt clumps lines of text." s.fold.assert == o leave spaces s = "This is\na test.\n\n This is pre.\n Leave alone.\n\nIt clumps\nlines of text." o = "This is a test.\n\n This is pre.\n Leave alone.\n\nIt clumps lines of text." s.fold(true).assert == o facets-2.9.3/qed/core/string/mscan.rdoc0000644000004100000410000000031311714455226020007 0ustar www-datawww-data== String#mscan require 'facets/string/mscan' r = 'abc,def,gh'.mscan(/[,]/) assert( r.all?{ |md| MatchData === md } ) r.to_a.length.assert == 2 r[0][0].assert == ',' r[1][0].assert == ',' facets-2.9.3/qed/core/string/rewrite.rdoc0000644000004100000410000000023511714455226020372 0ustar www-datawww-data== String#rewrite require 'facets/string/rewrite' s = "HELLO TOMMY!" rules = [[ /TOMMY/, 'MAN' ]] r = s.rewrite(rules) r.assert == "HELLO MAN!" facets-2.9.3/qed/core/string/each_char.rdoc0000644000004100000410000000022011714455226020600 0ustar www-datawww-data== String#each_char require 'facets/string/each_char' a = [] i = "this" i.each_char{ |w| a << w } a.assert == ['t', 'h', 'i', 's'] facets-2.9.3/qed/core/string/start_with.rdoc0000644000004100000410000000015111714455226021076 0ustar www-datawww-data== String#start_with? require 'facets/string/start_with' s = "xxboo" s.assert.start_with?('xx') facets-2.9.3/qed/core/string/op_sub.rdoc0000644000004100000410000000013311714455226020175 0ustar www-datawww-data== String#- 'facets/string/op_sub' s = "xxbooxxfoo" (s - "xx").assert == "boofoo" facets-2.9.3/qed/core/string/subtract.rdoc0000644000004100000410000000025411714455226020541 0ustar www-datawww-data== String#- require 'facets/string/subtract' ("foobar" - "oo").assert == "fbar" ("pizza pizza!" - "zz").assert == "pia pia!" ("letters" - /[a-z]+/).assert == "" facets-2.9.3/qed/core/string/align.rdoc0000644000004100000410000000173311714455226020007 0ustar www-datawww-data== String#align require 'facets/string/align' Align a string to a given position. This method simply delegates to the other three more specific align methods. "xxx".align(:right, 9).assert == " xxx" "xxx".align(:left, 9).assert == "xxx " == String#align_right Align a string to the right. The default alignment separation is a newline ("\n"). This can be changed as can be the padding string which defaults to a single space (' '). "xxx".align_right(9).assert == " xxx" == String#align_left Align a string to the left. The default alignment separation is a newline ("\n"). This can be changed as can be the padding string which defaults to a single space (' '). "xxx".align_left(9).assert == "xxx " == String#align_center Centers each line of a string. The default alignment separation is a new line ("\n"). This can be changed as can be the padding string which defaults to a single space (' '). "xxx".align_center(9).assert == " xxx " facets-2.9.3/qed/core/string/cleave.rdoc0000644000004100000410000000175211714455226020155 0ustar www-datawww-data== String#cleave require 'facets/string/cleave' no spaces short word s, x = 'whole', ['whole', ''] s.cleave.assert == x no spaces long word s, x = 'Supercalifragilisticexpialidocious' , ['Supercalifragilisticexpialidocious', ''] s.cleave.assert == x exact middle two words s, x = 'fancy split', ['fancy', 'split'] s.cleave.assert == x exact middle many words s, x = 'All good Rubyists know how to party', ['All good Rubyists', 'know how to party'] s.cleave.assert == x closer to start s, x = 'short splitter', ['short', 'splitter'] s.cleave.assert == x closer to start s, x = 'Four score and seven years ago...', ['Four score and', 'seven years ago...'] s.cleave.assert == x closer to start s, x = 'abc def ghijklm nop', ['abc def', 'ghijklm nop'] s.cleave.assert == x closer to end s, x = 'extended split', ['extended', 'split'] s.cleave.assert == x closer to end s, x = 'abc defghi jklm nop', [ 'abc defghi', 'jklm nop'] s.cleave.assert == x facets-2.9.3/qed/core/string/methodize.rdoc0000644000004100000410000000042711714455226020704 0ustar www-datawww-data== String#methodize require 'facets/string/methodize' module name a = "FooBase" r = "foo_base" a.methodize.assert == r path name a = "foo/base" r = "foo__base" a.methodize.assert == r name space a = "Foo::Base" r = "foo__base" a.methodize.assert == r facets-2.9.3/qed/core/string/shatter.rdoc0000644000004100000410000000030411714455226020360 0ustar www-datawww-data== String#shatter require 'facets/string/shatter' s = "

Thisisa test.

" r = s.shatter( /<.*?>/ ) x = ["

", "This", "", "is", "", "a test.", "

"] r.assert == x facets-2.9.3/qed/core/string/unindent.rdoc0000644000004100000410000000265711714455226020547 0ustar www-datawww-data== String#unindent require 'facets/string/unindent' We will use these two strings as a common basis for demonstration. ex1 = <<-EOF.gsub(/^\s*\|/,'') | I must go down to the seas again | The lonely sea and the sky | And all I want is a tall ship | And a star to steer her by EOF ex2 = <<-EOF.gsub(/^\s*\|/,'') | "Eek!" | She cried | As the mouse quietly scurried |by. EOF simple examples " xyz".unindent(-1).assert == " xyz" " xyz".unindent(0).assert == " xyz" " xyz".unindent(1).assert == " xyz" " xyz".unindent(2).assert == " xyz" " xyz".unindent(3).assert == "xyz" " xyz".unindent(4).assert == "xyz" large example unindented one space expected = <<-EOF.gsub(/^\s*\|/,'') | I must go down to the seas again | The lonely sea and the sky | And all I want is a tall ship | And a star to steer her by EOF actual = ex1.unindent(1) actual.assert == expected large example unindented four spaces expected = <<-EOF.gsub(/^\s*\|/,'') |I must go down to the seas again | The lonely sea and the sky |And all I want is a tall ship | And a star to steer her by EOF actual = ex1.unindent(4) actual.assert == expected unindent larger than current indention expected = <<-EOF.gsub(/^\s*\|/,'') |"Eek!" |She cried |As the mouse quietly scurried |by. EOF actual = ex2.unindent(100) actual.assert == expected facets-2.9.3/qed/core/string/unfold.rdoc0000644000004100000410000000027311714455226020202 0ustar www-datawww-data== String#unfold require 'facets/string/unfold' str = "This is a test of\nparagraph folding." res = str.unfold exp = "This is a test of paragraph folding." res.assert == exp facets-2.9.3/qed/core/string/quote.rdoc0000644000004100000410000000070011714455226020043 0ustar www-datawww-data== String#quote require 'facets/string/quote' The default is single quotes. 'hi'.quote.assert == %{"hi"} The type of quotes can be specified by name. 'hi'.quote(:single).assert == %{'hi'} 'hi'.quote(:double).assert == %{"hi"} 'hi'.quote(:back).assert == %{`hi`} They can also be specified by the first character of the name. 'hi'.quote(:s).assert == %{'hi'} 'hi'.quote(:d).assert == %{"hi"} 'hi'.quote(:b).assert == %{`hi`} facets-2.9.3/qed/core/string/splice.rdoc0000644000004100000410000000063211714455226020171 0ustar www-datawww-data== String#splice require 'facets/string/splice' a = "HELLO" a.splice(1).assert == "E" a.assert == "HLLO" range a = "HELLO" a.splice(1..2).assert == "EL" a.assert == "HLO" store a = "HELLO" a.splice(1, "X") a.assert == "HXLLO" This could be done if class of 2nd arg is checked. #Unit :splice_length # a = "HELLO" # a.splice(1,2).assert == "EL" # a.assert == "HLO" #end facets-2.9.3/qed/core/string/camelcase.rdoc0000644000004100000410000000250511714455226020630 0ustar www-datawww-data== String#Camelcase require 'facets/string/camelcase' The `camelcase` method converts snakecase strings into camelcase strings. "abc_xyz".camelcase.assert == "abcXyz" Continious underscore characters are treated as if a single underscore character. "abc____xyz".camelcase.assert == "abcXyz" Without an argument the first character is left alone. "Camel_case".camelcase.assert == "CamelCase" Passing +:upper+ or +true+ to #camelcase captializes the first letter. This is known as upper-camelcase. "Abc_xyz".camelcase(true).assert == "AbcXyz" "Abc____xyz".camelcase(:upper).assert == "AbcXyz" Where as passing +false+ or +:lower+ downcases the first character, known as lower-camelcase. "abc_xyz".camelcase(false).assert == "abcXyz" "abc____xyz".camelcase(false).assert == "abcXyz" "Abc_xyz".camelcase(:lower).assert == "abcXyz" "Abc____xyz".camelcase(:lower).assert == "abcXyz" By passing a match string to the method we can make +camelcase+ apply to each word in a string. "abc xyz".camelcase(' ').assert == "abcXyz" "abc xyz".camelcase(/\s/).assert == "abcXyz" "abc\txyz".camelcase(/\s/).assert == "abcXyz" "abc\nxyz".camelcase(/\s/).assert == "abcXyz" == String#lower_camelcase "abc_xyz".lower_camelcase.assert == "abcXyz" == String#upper_camelcase "abc_xyz".upper_camelcase.assert == "AbcXyz" facets-2.9.3/qed/core/string/word_wrap.rdoc0000644000004100000410000000221711714455226020717 0ustar www-datawww-data== String#word_wrap require 'facets/string/word_wrap' e = "abcde\n12345\nxyzwu\n" r = "abcde 12345 xyzwu".word_wrap(5) r.assert == e e = "abcd\n1234\nxyzw\n" r = "abcd 1234 xyzw".word_wrap(4) r.assert == e e = "abc\n123\n" r = "abc 123".word_wrap(4) r.assert == e e = "abc \n123\n" r = "abc 123".word_wrap(4) r.assert == e e = "abc \n123\n" r = "abc 123".word_wrap(4) r.assert == e == String#word_wrap! w = "abcde 12345 xyzwu" w.word_wrap!(5) w.assert == "abcde\n12345\nxyzwu\n" w = "abcd 1234 xyzw" w.word_wrap!(4) w.assert == "abcd\n1234\nxyzw\n" w = "abc 123" w.word_wrap!(4) w.assert == "abc\n123\n" w = "abc 123" w.word_wrap!(4) w.assert == "abc \n123\n" w = "abc 123" w.word_wrap!(4) w.assert == "abc \n123\n" # Unit :word_wrap do # assert_equal "abcde-\n12345-\nxyzwu\n", "abcde12345xyzwu".word_wrap(6,2) # assert_equal "abcd-\n1234-\nxyzw\n", "abcd1234xyzw".word_wrap(5,2) # assert_equal "abc \n123\n", "abc 123".word_wrap(4,2) # assert_equal "abc \n123\n", "abc 123".word_wrap(4,2) # assert_equal "abc \n123\n", "abc 123".word_wrap(4,2) # end facets-2.9.3/qed/core/string/bytes.rdoc0000644000004100000410000000015011714455226020033 0ustar www-datawww-data== String#bytes require 'facets/string/bytes' s = "abc" s.bytes.to_a.assert == s.unpack('C*') facets-2.9.3/qed/core/string/divide.rdoc0000644000004100000410000000026311714455226020156 0ustar www-datawww-data== String#divide require 'facets/string/divide' s = "

Thisisa test.

" d = s.divide(/<.*?>/) e = ["

This", "is", "a test.", "

"] d.assert == e facets-2.9.3/qed/core/string/characters.rdoc0000644000004100000410000000036011714455226021027 0ustar www-datawww-data== String#characters The String#chars methods simply splits a string into an Array of character strings. require 'facets/string/characters' "abc".characters.assert == ["a","b","c"] "ab\nc".characters.assert == ["a","b","\n","c"] facets-2.9.3/qed/core/string/natcmp.rdoc0000644000004100000410000000052411714455226020174 0ustar www-datawww-data== String#natcmp require 'facets/string/natcmp' "my_prog_v1.1.0".natcmp( "my_prog_v1.2.0").assert == -1 "my_prog_v1.2.0".natcmp("my_prog_v1.10.0").assert == -1 "my_prog_v1.2.0".natcmp( "my_prog_v1.1.0").assert == 1 "my_prog_v1.10.0".natcmp("my_prog_v1.2.0").assert == 1 "my_prog_v1.0.0".natcmp( "my_prog_v1.0.0").assert == 0 facets-2.9.3/qed/core/string/lines.rdoc0000644000004100000410000000023611714455226020024 0ustar www-datawww-data== String#lines Ruby 1.9 defined #lines to keep the newline character. require 'facets/string/lines' "a\nb\nc".lines.to_a.assert == ["a\n","b\n","c"] facets-2.9.3/qed/core/string/newlines.rdoc0000644000004100000410000000032611714455226020536 0ustar www-datawww-data== String#newlines Since Ruby 1.9 defined #lines to keep the newline character, we have defined #newlines to leave them out. require 'facets/string/newlines' "a\nb\nc".newlines.to_a.assert == ["a","b","c"] facets-2.9.3/qed/core/string/variablize.rdoc0000644000004100000410000000014511714455226021041 0ustar www-datawww-data== String#variablize require 'facets/string/variablize' s = "a" s.variablize.assert == "@a" facets-2.9.3/qed/core/string/modulize.rdoc0000644000004100000410000000042411714455226020541 0ustar www-datawww-data== String#modulize require 'facets/string/modulize' snakecase a = "foo_bar" r = "FooBar" a.modulize.assert == r path name a = "foo/bar" r = "Foo::Bar" a.modulize.assert == r on methodized string a = "foo__bar" r = "Foo::Bar" a.modulize.assert == r facets-2.9.3/qed/core/string/titlecase.rdoc0000644000004100000410000000017711714455226020673 0ustar www-datawww-data== String#titlecase require 'facets/string/titlecase' r = "try this out".titlecase x = "Try This Out" r.assert == x facets-2.9.3/qed/core/string/expand_tabs.rdoc0000644000004100000410000000241611714455226021204 0ustar www-datawww-data== String#expand_tab require 'facets/string/expand_tab' We will use this string as a basis for demonstration. tabs = <<-EOF.gsub(/^\s+\|/, '') | |\tOne tab | \tOne space and one tab | \t Six spaces, a tab, and a space EOF Expanding tabs 0. expected = <<-EOF.gsub(/^\s+\|/, '') | |One tab | One space and one tab | Six spaces, a tab, and a space EOF tabs.expand_tabs(0).assert == expected Expanding tabs 1. expected = <<-EOF.gsub(/^\s+\|/, '') | | One tab | One space and one tab | Six spaces, a tab, and a space EOF tabs.expand_tabs(1).assert == expected Expanding tabs 4. expected = <<-EOF.gsub(/^\s+\|/, '') | | One tab | One space and one tab | Six spaces, a tab, and a space EOF tabs.expand_tabs(4).assert == expected Expanding tabs 8. expected = <<-EOF.gsub(/^\s+\|/, '') | | One tab | One space and one tab | Six spaces, a tab, and a space EOF tabs.expand_tabs.assert == expected tabs.expand_tabs(8).assert == expected Expanding tabs 16. expected = <<-EOF.gsub(/^\s+\|/, '') | | One tab | One space and one tab | Six spaces, a tab, and a space EOF tabs.expand_tabs(16).assert == expected facets-2.9.3/qed/core/string/margin.rdoc0000644000004100000410000000276111714455226020174 0ustar www-datawww-data== String#margin require 'facets/string/margin' s = %q{ |ABC |123 |TEST }.margin s.assert == "ABC\n123\nTEST" s = %q{ |ABC |123 |TEST }.margin s.assert == "ABC\n123\nTEST" s = %q{|ABC |123 |TEST }.margin s.assert == "ABC\n123\nTEST" s = %q{ |ABC |123 |TEST}.margin s.assert == "ABC\n123\nTEST" s = %q{|ABC |123 |TEST}.margin s.assert == "ABC\n123\nTEST" s = %q{ |ABC |123 |TEST}.margin s.assert == "ABC\n123\nTEST" s = %q{ABC |123 |TEST }.margin s.assert == "ABC\n123\nTEST" spacing s = %q{ | ABC | 123 | TEST }.margin s.assert == " ABC\n 123\n TEST" s = %q{ |ABC |123 |TEST }.margin(1) s.assert == " ABC\n 123\n TEST" s = %q{ |ABC |123 |TEST }.margin(2) s.assert == " ABC\n 123\n TEST" s = %q{ ABC - 123 - TEST }.margin s.assert == " ABC\n 123\n TEST" random placement @volly = {} 100.times{ |n| k = [] a = [] 5.times{ |i| k << ( ( ' ' * Integer(rand*10) ) + '|' + i.to_s ) a << ( i.to_s ) } @volly[k.join("\n")] = a.join("\n") } @volly.each{ |k,v| k.margin.assert == v } facets-2.9.3/qed/core/string/snakecase.rdoc0000644000004100000410000000026211714455226020646 0ustar www-datawww-data== String#snakecase require 'facets/string/snakecase' 'my_name'.snakecase.assert == 'my_name' 'MyName'.snakecase.assert == 'my_name' 'URI'.snakecase.assert == 'uri' facets-2.9.3/qed/core/string/unquote.rdoc0000644000004100000410000000013311714455226020406 0ustar www-datawww-data== String#unquote require 'facets/string/unquote' "'this'".unquote.assert == "this" facets-2.9.3/qed/core/string/indent.rdoc0000644000004100000410000000246311714455226020177 0ustar www-datawww-data== String#indent require 'facets/string/indent' positive "xyz".indent(4).assert == ' xyz' " xyz".indent(2).assert == ' xyz' multiline positive "abc\nxyz".indent(2).assert == " abc\n xyz" zero 'xyz'.indent(0).assert == 'xyz' negative ' xyz'.indent(-2).assert == ' xyz' ' xyz'. indent(-2).assert == 'xyz' multiline negative " abc\n xyz".indent(-2).assert == " abc\n xyz" negative more than is possible ' xyz'.indent(-3).assert == 'xyz' non-space positive "xyz".indent(4, '-').assert == '----xyz' non-space zero 'xyz'.indent(0, '-').assert == 'xyz' non-space negative non-matching character ' xyz'.indent(-2, '-').assert == ' xyz' ' xyz'. indent(-2, '-').assert == ' xyz' non-space negative '----xyz'.indent(-2, '-').assert == '--xyz' '--xyz'.indent(-2, '-').assert == 'xyz' Special regular expresion characters are escaped. ensure '.' is treated literally and not as wildcard ' xyz'.indent(-2, '.').assert == ' xyz' '..xyz'.indent(-2, '.').assert == 'xyz' ensure '*' is treated literally and not as wildcard ' xyz'.indent(-2, '*').assert == ' xyz' '**xyz'.indent(-2, '*').assert == 'xyz' ensure '^' is treated literally and not as line start ' xyz'.indent(-2, '^').assert == ' xyz' '^^xyz'.indent(-2, '^').assert == 'xyz' facets-2.9.3/qed/core/string/capitalized.rdoc0000644000004100000410000000104011714455226021175 0ustar www-datawww-data== String#capitalized? String#capitalized? return true if a string begins with a capitalized letter, false otherwise. require 'facets/string/capitalized' 'Abc'.assert.capitalized? == String#downcase? In addition String#downcase? is provided which checks to see if the whole string is composed of lowercase letters. 'abc'.assert.downcase? #'abc'.assert.lowercase? == String#upcase? And String#upcase? which checks to see if the whole string is composed of uppercase letters. 'ABC'.assert.upcase? #'ABC'.assert.uppercase? facets-2.9.3/qed/core/string/tab.rdoc0000644000004100000410000000050611714455226017460 0ustar www-datawww-data== String#tab require 'facets/string/tab' a = "abc".tab(2) a.assert == " abc" If we add a new line we see that both are tabbed. a = "abc\nxyz".tab(2) a.assert == " abc\n xyz" Unlike #tabto, #tab indents all lines equally regardless of prior indention. a = "abc\n xyz".tab(2) a.assert == " abc\n xyz" facets-2.9.3/qed/core/string/to_re.rdoc0000644000004100000410000000065311714455226020025 0ustar www-datawww-data== String#to_re require 'facets/string/to_re' "abc".to_re.assert == /abc/ "a+bc".to_re.assert == /a+bc/ "a+bc".to_re(false).assert == /a+bc/ "a+bc".to_re(true).assert == /a\+bc/ escaped characters a = "?" b = /#{a.to_rx}/ assert( b =~ "?" ) == String#to_rx "abc".to_rx.assert == /abc/ "a+bc".to_rx.assert == /a\+bc/ "a+bc".to_rx(false).assert == /a+bc/ "a+bc".to_rx(true).assert == /a\+bc/ facets-2.9.3/qed/core/string/bracket.rdoc0000644000004100000410000000130311714455226020321 0ustar www-datawww-data== String#bracket require 'facets/string/bracket' 'X'.bracket('#').assert == '#X#' 'X'.bracket('x','!').assert == 'xX!' 'X'.bracket('{','}').assert == '{X}' 'X'.bracket('<').assert == '' 'X'.bracket('(').assert == '(X)' 'X'.bracket('[').assert == '[X]' 'X'.bracket('{').assert == '{X}' == String#bracket! a = 'X' ; a.bracket!('#') a.assert == '#X#' a = 'X' ; a.bracket!('x','!') a.assert == 'xX!' a = 'X' ; a.bracket!('{','}') a.assert == '{X}' a = 'X' ; a.bracket!('<') a.assert == '' a = 'X' ; a.bracket!('(') a.assert == '(X)' a = 'X' ; a.bracket!('[') a.assert == '[X]' a = 'X' ; a.bracket!('{') a.assert == '{X}' facets-2.9.3/qed/core/string/lchomp.rdoc0000644000004100000410000000026411714455226020175 0ustar www-datawww-data== String#lchomp require 'facets/string/lchomp' s = "xxboo" r = s.lchomp("xx") r.assert == "boo" == String#lchomp! s = "xxboo" s.lchomp!("xx") s.assert == "boo" facets-2.9.3/qed/core/string/end_with.rdoc0000644000004100000410000000013311714455226020507 0ustar www-datawww-data= String#end_with? require 'facets/string/end_with' "xxboo".assert.end_with?('boo') facets-2.9.3/qed/core/string/line_wrap.rdoc0000644000004100000410000000023311714455226020667 0ustar www-datawww-data== String#line_wrap require 'facets/string/line_wrap' "abc123".line_wrap(3).assert == "abc\n123\n" "abcd123".line_wrap(4).assert == "abcd\n123\n" facets-2.9.3/qed/core/string/range.rdoc0000644000004100000410000000062111714455226020004 0ustar www-datawww-data== String#range require 'facets/string/range' "a123a567a9".range(/123/).assert == (1..3) "a123a567a9".range(/a/).assert == (0..0) == String#range_all "a123a123a9".range_all(/123/).assert == [ (1..3), (5..7) ] "a123a567a9".range_all(/a/).assert == [ (0..0), (4..4), (8..8) ] == String#range_of_line a = "0123\n456\n78" x = [0..4, 5..8, 9..10] r = a.range_of_line r.assert == x facets-2.9.3/qed/core/string/xor.rdoc0000644000004100000410000000022511714455226017520 0ustar www-datawww-data== String#^ require 'facets/string/xor' r = "try this out" ^ "puddingsnacks" x = "\004\a\035D\035\006\016\000N\016\026\037" r.assert == x facets-2.9.3/qed/core/string/pathize.rdoc0000644000004100000410000000041511714455226020355 0ustar www-datawww-data== String#pathize require 'facets/string/pathize' module name a = "Foo::Base" x = "foo/base" a.pathize.assert == x path name a = "foo/base" x = "foo/base" a.pathize.assert == x name space a = "foo__base" x = "foo/base" a.pathize.assert == x facets-2.9.3/qed/core/string/nchar.rdoc0000644000004100000410000000032511714455226020004 0ustar www-datawww-data== String#nchar require 'facets/string/nchar' "abcxyz".nchar(3).assert == "abc" "abcxyz".nchar(-3).assert == "xyz" "abcxyz".nchar(3, 'HI').assert == "HIxyz" "abcxyz".nchar(-3, 'HI').assert == "abcHI" facets-2.9.3/qed/core/string/cleanlines.rdoc0000644000004100000410000000043311714455226021026 0ustar www-datawww-data== String#cleanlines Thre String#cleanlines method works essentially the same as String#lines, returning an Array of line strings, but it also removes trailing whitespace from each line. require 'facets/string/cleanlines' "a \n b \nc".cleanlines.to_a.assert == ["a","b","c"] facets-2.9.3/qed/core/hash/0000755000004100000410000000000011714455226015455 5ustar www-datawww-datafacets-2.9.3/qed/core/hash/recursively.rdoc0000644000004100000410000000115411714455226020703 0ustar www-datawww-data== Hash#recursively require 'facets/hash/recursively' h = {:a=>1, :b=>{:c=>3}} Without a block passed tot he #recursive method, the block passed to the enumeratig method will be used for both recursive and non-recursive yields. r = h.recursively.map{ |k,v| [k.to_s, v] } r.assert == [['a', 1], ['b', [['c', 3]]]] But if we pass a block to #recursive we can treat the recusive yield separately, which in turn allows us to manipulate the non-recursive yields with a different procedure. r = h.recursively{ |k,v| [k.to_s, v] }.map{ |k,v| [k.to_s,v.to_s] } r.assert == [['a','1'], ['b', [['c', '3']]]] facets-2.9.3/qed/core/dir/0000755000004100000410000000000011714455226015310 5ustar www-datawww-datafacets-2.9.3/qed/core/dir/ascend.rdoc0000644000004100000410000000042011714455226017412 0ustar www-datawww-data== Dir#ascend require 'facets/dir/ascend' path = 'A/B/C' tmp = [] Dir.ascend(path) do |d| tmp << d end tmp.assert == %w{A/B/C A/B A} Exclude current path. tmp = [] Dir.ascend(path, false) do |d| tmp << d end tmp.assert == %w{A/B A} facets-2.9.3/qed/core/dir/descend.rdoc0000644000004100000410000000023611714455226017567 0ustar www-datawww-data== Dir#descend require 'facets/dir/descend' path = 'A/B/C' tmp = [] Dir.descend(path) do |d| tmp << d end tmp.assert == %w{A A/B A/B/C} facets-2.9.3/qed/core/dir/parent.rdoc0000644000004100000410000000013011714455226017444 0ustar www-datawww-data== Dir#parent require 'facets/dir/parent' Dir.assert.parent?("a/b/c", "a/b/c/d") facets-2.9.3/qed/core/dir/recurse.rdoc0000644000004100000410000000120411714455226017626 0ustar www-datawww-data== Dir#recurse Given a directory 'recurse' containing: A.txt A/B.txt A/B/C.txt We can use #recurse to gather a complete recursive list of all the entries. require 'facets/dir/recurse' x = %w{ recurse/A recurse/A.txt recurse/A/B recurse/A/B.txt recurse/A/B/C.txt }.sort r = Dir.recurse('recurse').sort r.assert == x == Dir#ls_r Dir#ls_r is an alias for #recurse which can also be used to gather a complete recursive list of all the entries. x = %w{ recurse/A recurse/A.txt recurse/A/B recurse/A/B.txt recurse/A/B/C.txt }.sort r = Dir.ls_r('recurse').sort r.assert == x facets-2.9.3/qed/core/dir/multiglob.rdoc0000644000004100000410000000124711714455226020163 0ustar www-datawww-data== Dir#multiglob Dir#multglob is like Dir#glob but it can handle more than one match parameter at a time. Given a directory 'multiglob' containing: A.txt A/B.txt A/B/C.txt We can use #multglob to find multiple matches. require 'facets/dir/multiglob' x = %w{ multiglob/A multiglob/A.txt } r = Dir.multiglob('multiglob/A', 'multiglob/A.*').sort r.assert == x == Dir#multiglob_r Dir#multiglob_r is like #multiglob but automatically searches directories recrusively. x = %w{ multiglob/A multiglob/A/B multiglob/A.txt multiglob/A/B.txt multiglob/A/B/C.txt }.sort r = Dir.multiglob_r('multiglob/*').sort r.assert == x facets-2.9.3/qed/core/indexable.rdoc0000644000004100000410000000300411714455226017333 0ustar www-datawww-data= Indexable Indexable it a module, like Enumerable, but provides methods specific to an indexable collection. The Indexable module can be used independently, but Facets can also automatically use it to extend Array. require 'facets/array/indexable' == Indexable#head a = [1,2,3,4,5] a.head.assert = [1] == Indexable#tail a = [1,2,3,4,5] a.tail.assert = [2,3,4,5] == Indexable#foot a = [1,2,3,4,5] a.foot.assert = [5] == Indexable#body a = [1,2,3,4,5] a.body.assert = [1,2,3,4] == Indexable#mid a = [1,2,3,4,5] b = [1,2,3,4,5,6] a.mid.assert = 3 b.mid.assert = 4 a.mid(1).assert = 4 b.mid(1).assert = 5 b.mid(2).assert = 6 b.mid(-1).assert = 3 == Indexable#middle a = [1,2,3,4,5] b = [1,2,3,4,5,6] a.middle.assert = [3] b.middle.assert = [3,4] == Indexable#thru [0,1,2,3,4,5].thru(2,4).assert = [2,3,4] [0,1,2,3,4,5].thru(0,1).assert = [0,1] == Indexable#first= a = [1,2] a.first = 0 a.assert = [0,2] == Indexable#last= a = [1,2] a.last = 3 a.assert = [1,3] == Indexable#ends [1,2,3,4,5].ends.assert = 4 == Indexable#pos a = [1,2,3,4,5] a.pos(1).assert = 0 a.pos(-1).assert = 4 == Indexable#range a = [1,2,3,4,5] b = [1,2,3,4,5,6] a.range.assert = (0..4) b.range.assert = (0..5) a.range(2,4).assert = (1..3) b.range(2,3).assert = (1..2) b.range(4,2).assert = (3..1) == Indexable#first! a = [1,2,3] a.first!.assert = 1 a.assert = [2,3] == Indexable#last! a = [1,2,3] a.last!.assert = 3 a.assert = [1,2] facets-2.9.3/qed/core/module/0000755000004100000410000000000011714455226016017 5ustar www-datawww-datafacets-2.9.3/qed/core/module/cattr.rdoc0000644000004100000410000000137111714455226020007 0ustar www-datawww-data== Class#cattr require 'facets/module/cattr' class CAttrMockObject def initialize @@a = 10 end def b ; @@b ; end end Exception.refute.raised? do CAttrMockObject.class_eval{ cattr :a } end t = CAttrMockObject.new t.a.assert == 10 == Class#cattr_reader Exception.refute.raised? do CAttrMockObject.class_eval { cattr_reader :a } end t = CAttrMockObject.new t.a.assert == 10 == Class#cattr_writer Exception.refute.raised? do CAttrMockObject.class_eval { cattr_writer :b } end t = CAttrMockObject.new t.b = 5 t.b.assert == 5 == Class#cattr_accessor Exception.refute.raised? do CAttrMockObject.class_eval { cattr_accessor :c } end t = CAttrMockObject.new t.c = 50 t.c.assert == 50 facets-2.9.3/qed/core/module/class_extend.rdoc0000644000004100000410000000205011714455226021341 0ustar www-datawww-data== Module#class_extend require 'facets/module/class_extend' Module using class_extend mix = Module.new do def i ; end class_extend do def n ; 42 ; end def s ; self ; end end end Extends module mix.n.assert == 42 mix.s.assert == mix Has expected methods mix.instance_methods.map{ |m| m.to_s }.assert == ['i'] transfers class methods to including class mod = Module.new do include mix end mod.n.assert == 42 mod.s.assert == mod Doesn't overwrite instance methods c = Class.new do include mix def n ; 11 ; end end c.new.n.assert == 11 Is overridable via including module mod = Module.new do include mix class_extend do def n ; super + 1 ; end end end mod.n.assert == 43 # notice the difference! mod.s.assert == mod Transfers class methods thru multiple levels of include alt = Module.new do include mix class_extend do def n ; super + 1 ; end end end mod = Module.new do include alt end mod.n.assert == 43 mod.s.assert == mod facets-2.9.3/qed/core/module/copy_inheritor.rdoc0000644000004100000410000000073111714455226021726 0ustar www-datawww-data= Module#copy_inheritor require 'facets/module/copy_inheritor' We see copy_inheritor m = Module.new do copy_inheritor :koko, [] koko << 1 end c1 = Class.new do include m #inheritor :koko, [], :+ koko << 2 koko << 3 end c2 = Class.new do include m #inheritor :koko, [], :+ koko << 4 end copy_inheritor m.koko.assert == [1] c1.koko.assert == [1,2,3] c2.koko.assert == [1,4] facets-2.9.3/qed/core/module/method_space.rdoc0000644000004100000410000000154411714455226021327 0ustar www-datawww-data== Module#method_space require 'facets/module/method_space' class A attr_writer :x method_space :inside do def x; @x; end end end a = A.new a.x = 10 We can see that the `inside` method space has access to the instance space. a.inside.x #=> 10 But there is no reader in the instance space. expect NoMethodError do a.x end == Module#include_as require 'facets/module/include_as' Module#include_as utilizes #method_space to allow modules to be included within a separated namespace. module T def t ; "Tt" ; end def r ; "Tr" ; end def q ; super ; end end class N def q ; "Nq" ; end end class X < N include_as :test => T def n ; test.inspect ; end def m ; test.t ; end def o ; test.r ; end end x = X.new x.m.assert == "Tt" x.o.assert == "Tr" x.q.assert == "Nq" facets-2.9.3/qed/core/module/class_inheritor.rdoc0000644000004100000410000000371111714455226022062 0ustar www-datawww-data== Module#class_inheritor require 'facets/module/class_inheritor' Subclass with inheritor c = Class.new do class_inheritor :koko, [], :+ koko! << 1 end d = Class.new(c) do class_inheritor :koko, [], :+ koko! << 2 end We can see that c.koko!.assert == [1] c.koko.assert == [1] d.koko!.assert == [2] d.koko.assert == [1,2] Subclass without class_inheritor c = Class.new do class_inheritor :koko, [], :+ koko! << 1 end d = Class.new(c) Likewise c.koko!.assert == [1] c.koko.assert == [1] d.koko!.assert == [] d.koko.assert == [1] Include module with class_inheritor c = Class.new do class_inheritor :x, {}, :merge x![:a] = 1 end m = Module.new do class_inheritor :x, {}, :merge x![:b] = 2 end d = Class.new(c) do include m class_inheritor :x, {}, :merge x![:c] = 3 end Then c.x.assert == {:a=>1} m.x[:b].assert == 2 d.x.assert == {:a=>1,:b=>2,:c=>3} c.x[:a].assert == 1 c.x[:b].assert == nil c.x[:c].assert == nil d.x[:a].assert == 1 d.x[:b].assert == 2 d.x[:c].assert == 3 And d.x![:d] = 4 d.x[:d].assert == 4 Using #concat as the class_inheritor operator c = Class.new do class_inheritor :relations, [], :concat end d = Class.new(c) do #class_inheritor :relations, [], :concat end c.relations! << 1 c.relations! << 2 d.relations! << 3 Notice c.relations.assert == [1,2] d.relations.assert == [1,2,3] On Module m = Module.new do class_inheritor :koko, [], :+ koko! << 1 end c1 = Class.new do include m #class_inheritor :koko, [], :+ koko! << 2 koko! << 3 end c2 = Class.new do include m #class_inheritor :koko, [], :+ koko! << 4 end m.koko.assert == [1] c1.koko.assert == [1,2,3] c2.koko.assert == [1,4] facets-2.9.3/qed/standard/0000755000004100000410000000000011714455226015402 5ustar www-datawww-datafacets-2.9.3/qed/standard/04_equitable.rdoc0000644000004100000410000000077311714455226020540 0ustar www-datawww-data= Equitqable Require the library. require 'facets/equitable' We will use this simple class as an example. class C include Equitable(:a,:b) attr_accessor :a, :b def initialize(a,b) @a = a @b = b end end Now, if two instance of our sample class +C+ have equal attributes +@a+ and +@b+ then they will be equal. c1 = C.new(10,20) c2 = C.new(10,20) c2.assert == c1 Otherwise they will not be equal. c1 = C.new(10, 10) c2 = C.new(10, 20) c2.refute == c1 facets-2.9.3/qed/standard/basic_object.rdoc0000644000004100000410000000047511714455226020670 0ustar www-datawww-data== BasicObject require 'facets/basicobject' o = Class.new(BasicObject).new Should ignore new kernel methods. Kernel.module_eval { def xxx ; end } expect NoMethodError do o.xxx end Should ignore new object methods. Object.class_eval { def yyy ; end } expect NoMethodError do o.yyy end facets-2.9.3/qed/standard/02_cloneable.rdoc0000644000004100000410000000103311714455226020475 0ustar www-datawww-data= Cloneable Require the library. require 'facets/cloneable' We'll use this dummy class. class Foo include Cloneable def initialize @bar=[] end def bar_id @bar.object_id end end Try #dup. a = Foo.new b = a.dup b.bar_id.refute == a.bar_id a.taint b = a.dup b.assert.tainted? a.freeze b = a.dup b.refute.frozen? Note try #clone. a = Foo.new b = a.clone b.bar_id.refute == a.bar_id a.taint b = a.dup b.assert.tainted? a.freeze b = a.clone b.assert.frozen? facets-2.9.3/qed/standard/memoizable.rdoc0000644000004100000410000000657111714455226020410 0ustar www-datawww-data= Memoizable Memoizable allows require 'facets/memoizable' The classic example is calculating the Fibonacci sequence. class Fibonacci include Memoizable def fib( num ) return num if num < 2 fib(num - 1) + fib(num - 2) end memoize :fib end The first time will take a moment to calculate. f = Fibonacci.new f.fib(100) The second time will be returned almost instantly. f = Fibonacci.new f.fib(100) The following example makes if very clear what memoize is doing. class MemoExample include Memoizable attr_accessor :a memoize :a end m = MemoExample.new m.a = 10 m.a #=> 10 m.a = 20 m.a #=> 10 Even though @a is assigned to 20, the method #a continues to return 10. Memoizable is designed to handle a number of typically problematic aspects of memoization implementations. First a memoizable object can be frozen. f = Fibonacci.new f.freeze f.fib(100) Memoizable objects are freezable because it does not use an instance variable to store the memoized return values. Instead it uses a global class instance variable in +Memoizable.cache+. However, this also means the memoization cache is not preserved when an object is duplicated. If this behavior is desired an aditional module is provided called `Memoizable::Copy`. When the `Memoiazble::Copy` module is included into a class it not only adds the #memoize class methods but also includes an #initialize_copy method, which copies the appropriate cache entries when #dup or #clone is used. Keep this in mind. It is important to call #super if you override the #initialize_copy method in a class that uses `Memoizable::Copy`. class MemoExample2 include Memoizable::Copy attr_accessor :a memoize :a end m = MemoExample2.new m.a = 10 m.a #=> 10 n = m.dup n.a = 20 n.a #=> 10 The `#memoize` method also accepts a few options that can be used to modify the behvior of the memoizaiton. To memoize a method across all objects of the same class and not just per-object, set the `:class` option to true. class MemoExample3 include Memoizable attr_accessor :a memoize :a, :class=>true end m = MemoExample3.new m.a = 10 m.a #=> 10 n = MemoExample3.new n.a #=> 10 Memoization is indexed based on arguments passed to the method, as can be seen in the Fibonacci example. Methods can also be memoized by name only, forgoing any indexing based on arguments passed. To do this, set the `:arguments` option to +false+. class MemoExample4 include Memoizable def f(n) n + n end memoize :f, :arguments=>false end m = MemoExample4.new m.f(1) m.f(2) #=> 2 m.f(3) #=> 2 Blocks passed to a method normally have only a present vs. non-present effect on the memoization index. In other words the return value of a method will be cached under one key if a block is passed to it and under a different index if not. It doesn't matter if blocks passed in actually differ, since the only way to compare blocks is by their +object_id+ and it is very rare for the exact same block object to be reused. Finally, the `:freeze` option can be used to freeze the memoized results. class MemoExample5 include Memoizable def f(n) (n + n).to_s end memoize :f, :freeze=>true end m = MemoExample5.new m.f(1).frozen? #=> true m.f(2).frozen? #=> true facets-2.9.3/qed/standard/03_enumargs.rdoc0000644000004100000410000000275011714455226020402 0ustar www-datawww-data= Enumerable::Arguments Require the library. require 'facets/enumargs' This will serve as our example class. class PlusArray include Enumerable::Arguments def initialize(arr) @arr = arr end def each(n=0) @arr.each{ |e| yield(e+n) } end end Now Enumerable methods such as #map and #collect take an argument as well. t = PlusArray.new([1,2,3]) t.collect(4){ |e| e }.assert == [5,6,7] Filtering methods such as #select and reject work as well. t = PlusArray.new([1,2,3]) t.select(4){ |x| x == 6 }.assert == [6] t = PlusArray.new([1,2,3]) t.reject(4){ |x| x == 6 }.assert == [5,7] We can covert to an array using #to_a with an argument. t = PlusArray.new([1,2,3]) t.to_a(4).assert == [5,6,7] We can get the minimum value using #min. t = PlusArray.new([1,2,3]) t.min(4).assert == 5 And get the maximum value using #min. t = PlusArray.new([1,2,3]) t.max(4).assert == 7 Methods that already take and argument, now take two such as #include? t = PlusArray.new([1,2,3]) t.assert.include?(7,4) And #each_slice. t = PlusArray.new([1,2,3,4]) a = [] t.each_slice(2,4){ |e,f| a << [e,f] } a.assert == [[5,6],[7,8]] The #find method has a slightly different interface than the original Enumerable. t = PlusArray.new([1,2,3,4]) f = t.find(2, :ifnone=>lambda{:NOPE}) { |a| a == 10 } f.assert == :NOPE The #grep method should also work. t = PlusArray.new(['a1','b2','a3','b4']) t.grep(/^b/, 'x').assert == ['b2x','b4x'] facets-2.9.3/qed/standard/mulititon.rdoc0000644000004100000410000000634011714455226020302 0ustar www-datawww-data= Multiton The Multion pattern is essentially the same as the Singleton pattern, but unlike it's fully unique brethren Multiton's are identical if their initialization parameters are identical. To demontrate we first need to load the Facets multiton.rb script. require 'facets/multiton' Now for the various exmples. == EXAMPLE A - STANDARD USAGE class SomeMultitonClass include Multiton attr :arg def initialize(arg) @arg = arg end end a = SomeMultitonClass.instance(4) b = SomeMultitonClass.instance(4) # a and b are same object c = SomeMultitonClass.instance(2) # c is a different object a.assert == b x = [a.arg, b.arg].max * 10 + c.arg x.assert == 42 == EXAMPLE B - MODIFY AN EXISTING CLASS We can modify an existing class (if we are so bold), for example we can add shared filehandles to the File class. class ::File include Multiton end lineno = __LINE__ # HERE1 # HERE2 a = File.instance(__FILE__) b = File.instance(__FILE__) b.assert == a lineno.times{ a.gets } a.gets.strip.assert == "# HERE1" b.gets.strip.assert == "# HERE2" == EXAMPLE C - INHERITENCE class A < String include Multiton end # B is also a multiton - with it's OWN object cache class B < A; end # w is the same object as x, y is the same object as z w,x,y,z = A.instance('A'), A.instance('A'), B.instance('B'), B.instance('B') x.object_id.assert == w.object_id z.object_id.assert == y.object_id a = B.instance('A') b = B.instance('A') w.object_id.refute == a.object_id # (each class has it's own pool) b.object_id.assert == a.object_id == EXAMPLE D - MULTIPLE MODULE INCLUSION (does nothing) class A < String include Multiton end # B is also a multiton - with it's OWN object cache class B < A; end # w is the same object as x, y is the same object as z w,x,y,z = A.instance('A'), A.instance('A'), B.instance('B'), B.instance('B') yz_id = y.object_id || z.object_id If we include Multiton again, it will have to effect. B.class_eval { include Multiton } # y is not only the same object as z, but they are both the same object(s) # as from EXAMPLE C y,z = B.instance('B'), B.instance('B') yz_id.assert == y.object_id yz_id.assert == z.object_id == EXAMPLE E - SO YOU WANNA USE NEW INSTEAD OF INSTANCE module K # use an inner class which is itself a multiton class K < String; include Multiton; end # define a new which returns a mutltion using #instance... class << self def new(*args, &block) K.instance(*args, &block) end end end the = K.new '4' answer = K.new '2' x = sprintf( "%s%s", the, answer ) x.assert == "42" the.class.assert == K::K == EXAMPLE F - using Klass.multiton_id class Klass include Multiton def initialize( important, not_important ) @important, @not_important = important, not_important end def Klass.multiton_id(*args, &block) # we consider only the first arg important, not_important = *args important end end a = Klass.instance( :a, :b ) b = Klass.instance( :a, :c ) c = Klass.instance( :b, :b ) a.assert == b c.refute == a c.refute == b facets-2.9.3/qed/standard/05_instantiable.rdoc0000644000004100000410000000106111714455226021232 0ustar www-datawww-data= Instantiable Require the library. require 'facets/instantiable' We will use this module as an example. module M include Instantiable attr :a def initialize(a) @a = a end end As we can see M is now fully instantiable, as any class would be. m = M.new(1) m.a.assert == 1 We can also use #extend rather than #include and get the same result. module N extend Instantiable attr :a def initialize( a ) @a = a end end As we saw with +M+ so too with +N+. n = N.new( 1 ) n.a.assert == 1 facets-2.9.3/qed/applique/0000755000004100000410000000000011714455226015422 5ustar www-datawww-datafacets-2.9.3/qed/applique/file_helpers.rb0000644000004100000410000000141711714455226020413 0ustar www-datawww-datarequire 'fileutils' require 'pathname' def temporary_directory @temporary_directory ||= 'tmp' end Before :document do if File.exist?(temporary_directory) FileUtils.rm_r(temporary_directory) end FileUtils.mkdir(temporary_directory) end When /Given a directory '(.*?)' containing/ do |dir, text| #abort unless /^#{temporary_directory}/ =~ dir text.lines.each do |file| next if file =~ /^\s*$/ file = File.join(dir, file.strip) path = File.dirname(file) FileUtils.mkdir_p(path) File.open(file, 'w'){ |f| f << "SPINICH" } end end # Return project root directory by looking for +lib+ directory. def root_directory @root_directory ||= ( Pathname.new(Dir.pwd).ascend do |root| break root if root.join('lib').directory? end ) end facets-2.9.3/lib/0000755000004100000410000000000011714455226013577 5ustar www-datawww-datafacets-2.9.3/lib/core/0000755000004100000410000000000011714455226014527 5ustar www-datawww-datafacets-2.9.3/lib/core/facets.rb0000644000004100000410000000207611714455226016326 0ustar www-datawww-datarequire 'facets/version.rb' require 'facets/array.rb' require 'facets/binding.rb' require 'facets/boolean.rb' require 'facets/class.rb' require 'facets/comparable.rb' require 'facets/denumerable.rb' require 'facets/dir.rb' require 'facets/enumerable.rb' require 'facets/enumerator.rb' require 'facets/exception.rb' require 'facets/file.rb' require 'facets/filetest.rb' require 'facets/float.rb' require 'facets/functor.rb' require 'facets/hash.rb' require 'facets/indexable.rb' require 'facets/instance.rb' require 'facets/integer.rb' require 'facets/kernel.rb' require 'facets/lazy.rb' require 'facets/matchdata.rb' require 'facets/method.rb' require 'facets/module.rb' require 'facets/na.rb' require 'facets/nilclass.rb' require 'facets/numeric.rb' require 'facets/object.rb' require 'facets/objectspace.rb' require 'facets/proc.rb' require 'facets/process.rb' require 'facets/range.rb' require 'facets/regexp.rb' require 'facets/string.rb' require 'facets/struct.rb' require 'facets/symbol.rb' require 'facets/time.rb' require 'facets/to_hash.rb' require 'facets/unboundmethod.rb' facets-2.9.3/lib/core/facets/0000755000004100000410000000000011714455226015774 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/comparable/0000755000004100000410000000000011714455226020101 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/comparable/op_get.rb0000644000004100000410000000200711714455226021702 0ustar www-datawww-datamodule Comparable # Automatically generate comparitive definitions based on # attribute fields. # # include Comparable[:a, :b] # # is equivalent to including a module containing: # # def <=>(other) # cmp = self.a <=> other.a; return cmp unless cmp == 0 # cmp = self.b <=> other.b; return cmp unless cmp == 0 # 0 # end # def self.[](*accessors) Module.new do include Comparable define_method(:comparability){ accessors } define_method(:<=>) do |other| comparability.each do |a| cmp = (send(a) <=> other.send(a)) break cmp unless cmp == 0 end end end end end # Would it be nice if we could define comparability for all objects? # Then Comparable[] method would not be needed. Just: # # module Comparable # # def <=>(other) # comparability.each do |field| # cmp = send(field) <=> other.send(field); return cmp unless cmp == 0 # end # end # # end # # But I fear it might break other code. facets-2.9.3/lib/core/facets/comparable/clip.rb0000644000004100000410000000155111714455226021357 0ustar www-datawww-datamodule Comparable # Returns self if above the given lower bound, or # within the given lower and upper bounds, # otherwise returns the the bound of which the # value falls outside. # # 4.clip(3) #=> 4 # 4.clip(5) #=> 5 # 4.clip(2,7) #=> 4 # 9.clip(2,7) #=> 7 # 1.clip(2,7) #=> 2 # # CREDIT Florian Gross, Trans def clip(lower, upper=nil) return lower if self < lower return self unless upper return upper if self > upper return self end # Returns self if above the given lower bound, or # within the given lower and upper bounds, # otherwise returns the the bound of which the # value falls outside. # # 4.bound(3) #=> 4 # 4.bound(5) #=> 5 # 4.bound(2,7) #=> 4 # 9.bound(2,7) #=> 7 # 1.bound(2,7) #=> 2 # # CREDIT: Florian Gross alias_method :bound, :clip end facets-2.9.3/lib/core/facets/comparable/cmp.rb0000644000004100000410000000144311714455226021207 0ustar www-datawww-datamodule Comparable # Alternate name for comparison operator #<=>. # # 3.cmp(1) #=> 1 # 3.cmp(3) #=> 0 # 3.cmp(10) #=> -1 # # This fundamental compare method is used to keep # comparison compatible with #succ. # # CREDIT: Peter Vanbroekhoven def cmp(o) self<=>o end end class String # Compare method that takes length into account. # Unlike #<=>, this is compatible with #succ. # # "abc".cmp("abc") #=> 0 # "abcd".cmp("abc") #=> 1 # "abc".cmp("abcd") #=> -1 # "xyz".cmp("abc") #=> 1 # # CREDIT: Peter Vanbroekhoven # # TODO: Move String#cmp to string/ directory. def cmp(other) return -1 if length < other.length return 1 if length > other.length self <=> other # alphabetic compare end end facets-2.9.3/lib/core/facets/comparable/at_most.rb0000644000004100000410000000004011714455226022066 0ustar www-datawww-datarequire 'facets/comparable/cap' facets-2.9.3/lib/core/facets/comparable/bound.rb0000644000004100000410000000004111714455226021530 0ustar www-datawww-datarequire 'facets/comparable/clip' facets-2.9.3/lib/core/facets/comparable/cap.rb0000644000004100000410000000103411714455226021167 0ustar www-datawww-datamodule Comparable # Returns the lower of self or x. # # 4.at_least(5) #=> 5 # 6.at_least(5) #=> 6 # # CREDIT: Florian Gross def at_least(lower) (self >= lower) ? self : lower end # Returns the greater of self or x. # # 4.at_most(5) #=> 4 # 6.at_most(5) #=> 5 # # CREDIT: Florian Gross def at_most(upper) (self <= upper) ? self : upper end # Returns the greater of self or x. # # 4.cap(5) #=> 4 # 6.cap(5) #=> 5 # # CREDIT: Trans alias_method :cap, :at_most end facets-2.9.3/lib/core/facets/comparable/at_least.rb0000644000004100000410000000004011714455226022214 0ustar www-datawww-datarequire 'facets/comparable/cap' facets-2.9.3/lib/core/facets/integer.rb0000644000004100000410000000060211714455226017754 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'integer/bit.rb' require_relative 'integer/bitmask.rb' require_relative 'integer/even.rb' require_relative 'integer/factorial.rb' require_relative 'integer/multiple.rb' require_relative 'integer/odd.rb' require_relative 'integer/of.rb' require_relative 'integer/ordinal.rb' #require_relative 'integer/roman.rb' # uncommon facets-2.9.3/lib/core/facets/comparable.rb0000644000004100000410000000047511714455226020434 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'comparable/at_least.rb' require_relative 'comparable/at_most.rb' require_relative 'comparable/bound.rb' require_relative 'comparable/cap.rb' require_relative 'comparable/clip.rb' require_relative 'comparable/cmp.rb' require_relative 'comparable/op_get.rb' facets-2.9.3/lib/core/facets/nilclass/0000755000004100000410000000000011714455226017604 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/nilclass/ergo.rb0000644000004100000410000000003511714455226021063 0ustar www-datawww-datarequire 'facets/kernel/ergo' facets-2.9.3/lib/core/facets/nilclass/to_f.rb0000644000004100000410000000034011714455226021055 0ustar www-datawww-dataclass NilClass unless method_defined?(:to_f) # Allows nil to respond to #to_f. # Always returns 0. # # nil.to_f #=> 0.0 # # CREDIT: Matz def to_f; 0.0; end end end facets-2.9.3/lib/core/facets/range/0000755000004100000410000000000011714455226017070 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/range/to_r.rb0000644000004100000410000000061411714455226020361 0ustar www-datawww-dataclass Range # A thing really should know itself. # This simply returns _self_. # # CREDIT: Trans def to_r self end # A thing really should know itself. # This simply returns _self_. # # Note: This does not internally effect the Ruby # interpretor such that it can coerce Range-like # objects into a Range. # # CREDIT: Trans def to_range self end end facets-2.9.3/lib/core/facets/range/overlap.rb0000644000004100000410000000026111714455226021064 0ustar www-datawww-dataclass Range # Do two ranges overlap? # # CREDIT: Daniel Schierbeck, Brandon Keepers def overlap?(other) include?(other.first) or other.include?(first) end end facets-2.9.3/lib/core/facets/range/within.rb0000644000004100000410000000221411714455226020716 0ustar www-datawww-dataclass Range # Uses the Range#umbrella method to determine # if another Range is _anywhere_ within this Range. # # (1..3).within?(0..4) #=> true # # CREDIT: Trans def within?(rng) case rng.umbrella(self) when [0,0], [-1,0], [0,-1], [-1,-1] return true else return false end end # Returns a two element array of the relationship # between two Ranges. # # Diagram ... # # Relationship Returns # # self |-----------| # r |-----------| [0,0] # # self |-----------| # r |---------| [-1,-1] # # self |---------| # r |-----------| [1,1] # # self |-----------| # r |----------| [-1,0] # # self |-----------| # r |-----------| [-1,1] # # etc. # # Example: # # (0..3).umbrella(1..2) #=> [-1,-1] # # CREDIT: Trans, Chris Kappler def umbrella(r) s = first <=> r.first e = r.last <=> last if e == 0 if r.exclude_end? and exclude_end? e = r.max <=> max else e = (r.exclude_end? ? 0 : 1) <=> (exclude_end? ? 0 : 1) end end return s,e end end facets-2.9.3/lib/core/facets/range/quantile.rb0000644000004100000410000000060411714455226021237 0ustar www-datawww-dataclass Range # Calculate the kth n-tile in a range. # # If n=4 the quantity is called a quartile, and if n=100 # it is called a percentile. # # @uncommon # require 'facets/range/quantile' # # @return [Integer] the kth n-tile def quantile(k, n=100) return 1 if k < first return n if k >= last ((k - first) / ((last - first) / n.to_f)).to_i + 1 end end facets-2.9.3/lib/core/facets/range/umbrella.rb0000644000004100000410000000003611714455226021217 0ustar www-datawww-datarequire 'facets/range/within' facets-2.9.3/lib/core/facets/range/combine.rb0000644000004100000410000000164311714455226021035 0ustar www-datawww-dataclass Range # Combine ranges. # # (1..2).combine(2..4) #=> [1..4] # (1..2).combine(3..4) #=> [1..2, 3..4] # # TODO: Incorporate end-sentinal inclusion vs. exclusion. # # CREDIT: Trans def combine(*intervals) Range.combine(self, *intervals) end # Combine intervals. # # Range.combine(1..2, 2..4) #=> [1..4] # Range.combine(1..2, 3..4) #=> [1..2, 3..4] # # CREDIT: Trans def self.combine(*intervals) intype = intervals.first.class result = [] intervals = intervals.collect do |i| [i.first, i.last] end intervals.sort.each do |(from, to)| #inject([]) do |result, if result.empty? or from > result.last[1] result << [from, to] elsif to > result.last[1] result.last[1] = to end #result end if intype <= Range result.collect{ |i| ((i.first)..(i.last)) } else result end end end facets-2.9.3/lib/core/facets/version.rb0000644000004100000410000000046611714455226020014 0ustar www-datawww-datamodule Facets # def self.profile @profile ||= ( require 'yaml' YAML.load(File.new(File.dirname(__FILE__) + '/facets.yml')) ) end # def self.const_missing(name) key = name.to_s.downcase profile[key] || super(name) end # VERSION = '2.9.3' # profile['version'] end facets-2.9.3/lib/core/facets/filetest/0000755000004100000410000000000011714455226017613 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/filetest/relative.rb0000644000004100000410000000160411714455226021754 0ustar www-datawww-datarequire 'facets/filetest/separator_pattern' module FileTest module_function # Predicate method for testing whether a path is absolute. # It returns +true+ if the pathname begins with a slash. def absolute?(path) !relative?(path) end # The opposite of #absolute? def relative?(path) while r = chop_basename(path.to_s) path, basename = r end path == '' end # List File.split, but preserves the file separators. # # FileTest.chop_basename('/usr/lib') #=> ['/usr/', 'lib'] # FileTest.chop_basename('/') #=> nil # # Returns Array of `[pre-basename, basename]` or `nil`. # # This method is here simply to support the #relative? and #absolute? methods. def chop_basename(path) base = File.basename(path) if /\A#{SEPARATOR_PATTERN}?\z/ =~ base return nil else return path[0, path.rindex(base)], base end end end facets-2.9.3/lib/core/facets/filetest/absolute.rb0000644000004100000410000000004311714455226021753 0ustar www-datawww-datarequire 'facets/filetest/relative' facets-2.9.3/lib/core/facets/filetest/contains.rb0000644000004100000410000000035511714455226021761 0ustar www-datawww-datamodule FileTest module_function # Does the +parent+ contain the +child+? def contains?(child, parent=Dir.pwd) parent = File.expand_path(parent) child = File.expand_path(child) child.sub(parent,'') != child end end facets-2.9.3/lib/core/facets/filetest/root.rb0000644000004100000410000000042011714455226021117 0ustar www-datawww-datamodule FileTest module_function # Is the specified directory the root directory? # # CREDIT: Jeffrey Schwab def root?(dir=nil) pth = File.expand_path(dir||Dir.pwd) return true if pth == '/' return true if pth =~ /^(\w:)?\/$/ false end end facets-2.9.3/lib/core/facets/filetest/separator_pattern.rb0000644000004100000410000000047211714455226023700 0ustar www-datawww-datamodule FileTest # SEPARATOR_PATTERN = ( if File::ALT_SEPARATOR /[#{Regexp.quote File::ALT_SEPARATOR}#{Regexp.quote File::SEPARATOR}]/ else /#{Regexp.quote File::SEPARATOR}/ end ).freeze #module_function # # # # def separator_pattern # SEPARATOR_PATTERN # end end facets-2.9.3/lib/core/facets/filetest/safe.rb0000644000004100000410000000053411714455226021060 0ustar www-datawww-datarequire 'facets/filetest/separator_pattern' module FileTest module_function # Is a path considered reasonably "safe"? # # Do not mistake this for a perfect solution! def safe?(path) case path when /\A(#{SEPARATOR_PATTERN}|\~)(#{SEPARATOR_PATTERN}|\*)+/ false else true end end end facets-2.9.3/lib/core/facets/objectspace.rb0000644000004100000410000000025211714455226020602 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'objectspace/classes.rb' require_relative 'objectspace/op_fetch.rb' require_relative 'objectspace/reflect.rb' facets-2.9.3/lib/core/facets/matchdata.rb0000644000004100000410000000017211714455226020247 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'matchdata/match.rb' require_relative 'matchdata/matchset.rb' facets-2.9.3/lib/core/facets/indexable.rb0000644000004100000410000001307411714455226020261 0ustar www-datawww-data# Indexable is a mixin that provides index based methods, # working soley with four methods: #index, #slice, #splice # and #size. # # These methods work in harmony. Where #index returns a # position of a given element, #slice returns elements # for given positions. #splice is like #slice but replaces # the given position with new values. This mehtod is not # part of ruby core, but it generally just an alias for #[]=, # just as #slice is an alias of #[]. #size of course simply # returns the total length of the indexable object. # # NOTE: To test the folowing methods Indexable needs to be # included into Array and array must have #splice defined. # # require 'facets/array/splice' # # class ::Array # include Indexable # end # # CREDIT: Thomas Sawyer module Indexable # Like #first but returns the first element # in a new array. # # [1,2,3].head #=> [1] # def head slice(0,1) end # Returns an array from second element to last element. # # [1,2,3].tail #=> [2,3] # def tail slice(1,length-1) end # Like #last, returning the last element # in an array. # # [1,2,3].foot #=> [3] # def foot slice(-1,1) end # Returns an array of the first element upto, # but not including, the last element. # # [1,2,3].body #=> [1,2] # #-- # Better name for this? (bulk, perhaps?) #++ # def body slice(0,size-1) end # Returns the middle element of an array, or the element offset # from middle if the parameter is given. Even-sized arrays, # not having an exact middle, return the middle-right element. # # [1,2,3,4,5].mid #=> 3 # [1,2,3,4,5,6].mid #=> 4 # [1,2,3,4,5,6].mid(-1) #=> 3 # [1,2,3,4,5,6].mid(-2) #=> 2 # [1,2,3,4,5,6].mid(1) #=> 5 # # In other words, If there are an even number of elements the # higher-indexed of the two center elements is indexed as # orgin (0). # def mid(offset=0) slice((size / 2) + offset) end # Returns an Array of the middle element(s) of an array. # Even-sized arrays, not having an exact middle, return # a two-element array of the two middle elements. # # [1,2,3,4,5].middle #=> [3] # [1,2,3,4,5,6].middle #=> [3,4] # # A +birth+ can be give to widen the middle on either side. # # [1,2,3,4,5].middle(1) #=> [2,3,4] # [1,2,3,4,5,6].middle(1) #=> [2,3,4,5] # # In contrast to #mid which utilizes an offset. # def middle(birth=0) i = size / 2 - birth if size % 2 == 0 slice(i - 1, 2 + (2 * birth)) else slice(i, 1 + (2 * birth)) end end # Fetch values from a start index thru an end index. # # [1,2,3,4,5].thru(0,2) #=> [1,2,3] # [1,2,3,4,5].thru(2,4) #=> [3,4,5] # # [1,2,3,4,5].thru(2) #=> [1,2,3] # [1,2,3,4,5].thru(4) #=> [1,2,3,4,5] # def thru(from, to=nil) from, to = 0, from unless to to = size - 1 if to >= size a = [] i = from while i <= to a << slice(i) i += 1 end a end # Returns last _n_ elements. # # %w{W o r l d}.from(3) #=> %w{l d} # def from(i) return self if i >= size slice(i, size - i) #slice(-n..-1) end ## DEPRECATED: use #thru instead ## Returns first _n_ elements. ## ## %w{H e l l o}.upto(3) #=> %w{H e l l} ## ##def upto(n) ## slice(0, n.to_i+1) ##end # Returns first _n_ elements. # # %w{H e l l o}.first(3) #=> %w{H e l} # def first(n=1) slice(0, n.to_i) end # Returns last _n_ elements. # # %w{H e l l o}.last(3) #=> %w{l l o} # def last(n=1) n = n.to_i return self if n > size slice(-n, n) #slice(-n..-1) end # Change the first element. # # a = ["a","y","z"] # a.first = "x" # a #=> ["x","y","z"] # def first=(x) splice(0,x) end # Change the last element. # # a = [1,2,5] # a.last = 3 # a #=> [1,2,3] def last=(x) splice(-1,x) end # Remove and return the first element. # # a = [1,2,3] # a.first! #=> 1 # a #=> [2,3] # def first! splice(0) end # Remove and return the last element. # # a = [1,2,3] # a.last! #=> 3 # a #=> [1,2] # def last! splice(-1) end # A shorting of "ends at", returns the # last index of the indexable object. # Returns nil if there are no elements. # # [1,2,3,4,5].ends #=> 4 # # This nearly equivalent to +size - 1+. # def ends return nil if size == 0 size - 1 end # Returns the positive ordinal index given # a cardinal position, 1 to n or -n to -1. # # [1,2,3,4,5].pos(1) #=> 0 # [1,2,3,4,5].pos(-1) #=> 4 # def pos(i) if i > 0 return i - 1 else size + i end end # Returns the index of the first element equal to the # given object or satisfying the block condition. # # [1,2,3,4].index{ |e| e == 3 } #=> 2 # [1,2,3,4].index{ |e| e > 3 } #=> 3 # def index(obj=nil, &block) if block_given? size.times do |i| return i if yield(slice(i)) end else size.times do |i| return i if obj == slice(i) end end nil end # to be deprecated alias_method :index_of, :index # TODO Maybe #range could use a little error catch code (todo). # Returns the index range between two elements. If no elements are # given, returns the range from first to last. # # ['a','b','c','d'].range #=> (0..3) # ['a','b','c','d'].range('b','d') #=> (1..3) # def range(a=nil,z=-1) if a index(a)..index(z) else (0..(size-1)) end end end facets-2.9.3/lib/core/facets/metaid.rb0000644000004100000410000000030611714455226017563 0ustar www-datawww-datarequire 'facets/kernel/meta_alias' require 'facets/kernel/meta_class' require 'facets/kernel/meta_def' require 'facets/kernel/meta_eval' # in remberence of _why require 'facets/kernel/eigenclass' facets-2.9.3/lib/core/facets/proc.rb0000644000004100000410000000043411714455226017265 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'proc/bind.rb' require_relative 'proc/bind_to.rb' require_relative 'proc/compose.rb' require_relative 'proc/curry.rb' require_relative 'proc/partial.rb' require_relative 'proc/to_method.rb' require_relative 'proc/update.rb' facets-2.9.3/lib/core/facets/boolean.rb0000644000004100000410000000375311714455226017750 0ustar www-datawww-datarequire 'facets/kernel/true' require 'facets/kernel/false' module Kernel # Boolean conversion for not being nil or false. # Other classes may redefine this to suite the # particular need. # # "yes".to_b #=> true # "abc".to_b #=> false # # true.to_b #=> true # false.to_b #=> false # nil.to_b #=> false # # CREDIT: Ara T. Howard, Trans def to_b self ? true : false end # All objects except false and nil are "true". def to_bool true end # Returns true is an object is class TrueClass # or FalseClass, otherwise false. # # true.bool? #=> true # false.bool? #=> true # nil.bool? #=> false # def bool? (true == self or false == self) end end class TrueClass def to_bool self end end class FalseClass def to_bool self end end class NilClass def to_bool false end end class Numeric # Provides a boolean interpretation of self. # If self == 0 then false else true. # # 0.to_b #=> false # 1.to_b #=> true # 2.3.to_b #=> true # def to_b self == 0 ? false : true end end class String # Interpret common affirmative string meanings as true, # otherwise nil or false. Blank space and case are ignored. # The following strings that will return true ... # # true # yes # on # t # 1 # y # == # # The following strings will return nil ... # # nil # null # # All other strings return false. # # Here are some exmamples. # # "true".to_b #=> true # "yes".to_b #=> true # "no".to_b #=> false # "123".to_b #=> false # def to_b case self.downcase.strip when 'true', 'yes', 'on', 't', '1', 'y', '==' return true when 'nil', 'null' return nil else return false end end end class Array # Boolean conversion for not empty? def to_b ! self.empty? end end class Hash # Boolean conversion for not empty? def to_b ! self.empty? end end facets-2.9.3/lib/core/facets/regexp/0000755000004100000410000000000011714455226017266 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/regexp/arity.rb0000644000004100000410000000051711714455226020746 0ustar www-datawww-dataclass Regexp # Returns the number of backreferencing subexpressions. # # /(a)(b)(c)/.arity #=> 3 # /(a(b(c)))/.arity #=> 3 # # Note that this is not perfect, especially with regards to \x # and embedded comments. # # CREDIT: Trans def arity source.scan( /(?!\\)[(](?!\?[#=:!>-imx])/ ).length end end facets-2.9.3/lib/core/facets/regexp/op_add.rb0000644000004100000410000000041611714455226021042 0ustar www-datawww-dataclass Regexp # Add regular expressions. # # /a/ + /b/ == /(?-mix:a)(?-mix:b)/ # # Functionally equivalent to: # # /ab/ # # CREDIT: Tyler Rick def +(other) other = Regexp.escape(other) if other.is_a?(String) /#{self}#{other}/ end end facets-2.9.3/lib/core/facets/regexp/multiline.rb0000644000004100000410000000030011714455226021606 0ustar www-datawww-dataclass Regexp # Is a regular expression multiline? # # /x/.multiline? #=> false # /x/m.multiline? #=> true # def multiline? options & MULTILINE == MULTILINE end end facets-2.9.3/lib/core/facets/regexp/op_or.rb0000644000004100000410000000043211714455226020730 0ustar www-datawww-dataclass Regexp # Operator form of `Regexp.union`. # # /a/ | /b/ #=> /(?-mix:a)|(?-mix:b)/ # # If +other+ is not a Regexp it is passed to Regexp.escape. # def |(other) other = Regexp.escape(other) unless Regexp === other Regexp.union(self, other) end end facets-2.9.3/lib/core/facets/regexp/to_re.rb0000644000004100000410000000125711714455226020730 0ustar www-datawww-dataclass Regexp # Like #to_re, but following Ruby's formal definitions, # only a Regular expression type object will respond to this. # # Note that to be of much real use this should be defined in core Ruby. # # CREDIT: Florian Gross def to_regexp self end # Simply returns itself. Helpful when converting # strings to regular expressions, where regexp # might occur as well --in the same vien as using # #to_s on symbols. The parameter is actaully a # dummy parameter to coincide with String#to_re. # # /abc/.to_re #=> /abc/ # # CREDIT: Trans def to_re(esc=false) self # Of course, things really should know how to say "I" ;) end end facets-2.9.3/lib/core/facets/functor.rb0000644000004100000410000000441111714455226020001 0ustar www-datawww-data# By definition a Functor is simply a first class method, but these are common # in the form of Method and Proc. So for Ruby a Functor is a more specialized # as a Higher-order function or Metafunction. Essentally, a Functor can vary # its behavior accorrding to the operation applied to it. # # f = Functor.new { |op, x| x.send(op, x) } # (f + 1) #=> 2 # (f + 2) #=> 4 # (f + 3) #=> 6 # (f * 1) #=> 1 # (f * 2) #=> 4 # (f * 3) #=> 9 # class Functor #< BasicObject # Functors can be somewhat inefficient if a new Functor # is frequently recreated for the same use. So this cache # can be used to speed things up. # # The +key+ will always be an array, wich makes it easier # to cache functor for multiple factors. # def self.cache(*key, &function) @cache ||= {} if function @cache[key] = new(&function) else @cache[key] end end EXCEPTIONS = [:binding, :inspect, :object_id] if defined?(::BasicObject) EXCEPTIONS.concat(::BasicObject.instance_methods) EXCEPTIONS.uniq! EXCEPTIONS.map!{ |m| m.to_sym } end # alias :__class__ :class ## If Functor were built-in to Ruby this would not be ## needed since exceetions could just be added directly. ##$FUNCTOR_EXCEPTIONS ||= [:binding, :undefine_method] ## TODO: This will not work when BasicObject is utilized. How to fix? ##def self.honor_exceptions ## $FUNCTOR_EXCEPTIONS.each{ |name| ## next if method_defined?(name) ## eval %{ ## def #{name}(*a,&b) ## super(*a, &b) ## end ## } ## } ##end # Privatize all methods except vital methods and #binding. instance_methods(true).each do |m| next if m.to_s =~ /^__/ next if EXCEPTIONS.include?(m.to_sym) undef_method(m) end # def initialize(&function) @function = function end # def to_proc @function end ##def inspect ## #"#" # hex id ? ## "#{method_missing(:inspect)}" ##end ## Needed? ##def send(op, *a, &b) ## method_missing(op, *a, &b) ##end private # Any action against the functor is processesd by the function. def method_missing(op, *args, &blk) @function.call(op, *args, &blk) end end # Copyright (c) 2004 Thomas Sawyer (Ruby License) facets-2.9.3/lib/core/facets/na.rb0000644000004100000410000000071511714455226016722 0ustar www-datawww-data# N/A exception is useful for specifying non-argument defaults when +nil+ # is a valid value. # # def f(x=NA) # end # # NA is also used to represent an argument "slot" for Proc#partial. # # NA is an instance of ArgumentError. class << NA = ArgumentError.new def inspect ; 'N/A' ; end def method_missing(*); self; end end # NA is a subclass of ArgumentError. #class NA < ArgumentError # class << self # def method_missing(*); self; end # end #end facets-2.9.3/lib/core/facets/array/0000755000004100000410000000000011714455226017112 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/array/divide.rb0000644000004100000410000000044511714455226020706 0ustar www-datawww-dataclass Array # Divide on matching pattern. # # ['a1','b1','a2','b2'].divide(/^a/) # #=> [['a1','b1'],['a2','b2']] # # CREDIT: Trans def divide(pattern) memo = [] each do |obj| memo.push [] if pattern === obj memo.last << obj end memo end end facets-2.9.3/lib/core/facets/array/recursively.rb0000644000004100000410000000241111714455226022011 0ustar www-datawww-datarequire 'facets/functor' require 'facets/enumerable/recursively' class Array # Apply a method to array, and recursively apply that method # to each sub-array or +types+. # # arr = ["a", ["b", "c"]] # arr.recursively.map{ |v| v.to_sym } # #=> [:a, [:b, :c]] # # By default the sub-types are passed thru uneffected. Passing a block # to #recursively changes this. # # arr = ["a", ["b", "c"]] # arr.recursively{ |a| a.reverse }.map{ |v| v.to_sym } # #=> [:a, [:c, :b]] # # TODO: Return Enumerator if no +yld+ block is given ? def recursively(*types, &block) Recursor.new(self, *types, &block) end ## TODO: When no longer needing to support 1.8.6 we could get rid of ## the Recursor class and use: ## ## def recursively(*types, &block) ## types = types.empty? ? [self.class] : types ## Functor.new do |op, &yld| ## rec = block || lambda{ |a| a } ## yld = yld || lambda{ |v| v } # ? to_enum ## __send__(op) do |v| ## case v ## when String # b/c of 1.8 ## yld.call(v) ## when *types ## res = v.recursively(*types, &block).__send__(op,&yld) ## rec.call(res) ## else ## yld.call(v) ## end ## end ## end ## end end facets-2.9.3/lib/core/facets/array/each_pair.rb0000644000004100000410000000033511714455226021353 0ustar www-datawww-dataclass Array # Iterate over index and value. The intention of this # method is to provide polymorphism with Hash. # def each_pair #:yield: i = -1 each_value do |x| yield(i+=1, x) end end end facets-2.9.3/lib/core/facets/array/select.rb0000644000004100000410000000051411714455226020716 0ustar www-datawww-dataclass Array unless method_defined?(:select!) # As with #select but modifies the Array in place. # # a = [1,2,3,4,5,6,7,8,9,10] # a.select!{ |e| e % 2 == 0 } # a #=> [2,4,6,8,10] # # CREDIT: Gavin Sinclair # def select! # :yield: reject!{ |e| not yield(e) } end end end facets-2.9.3/lib/core/facets/array/median.rb0000644000004100000410000000122511714455226020674 0ustar www-datawww-dataclass Array # Determines the _sorted_ middle element. # # a = %w{a a b b c c c} # a.median #=> "b" # # When there are an even number of elements, the greater # of the two middle elements is given. # # a = %w{a a b b c c c d} # a.median #=> "c" # # An offset can be supplied to get an element relative # to the middle. # # a = %w{a a b b c c c d} # a.median(-1) #=> "b" # # The the array is empty, +nil+ is returned. # # @return [Object] sorted middle element def median(offset=0) return nil if self.size == 0 tmp = self.sort mid = (tmp.size / 2).to_i + offset tmp[mid] end end facets-2.9.3/lib/core/facets/array/uniq_by.rb0000644000004100000410000000051611714455226021107 0ustar www-datawww-dataclass Array # Like #uniq, but determines uniqueness based on a given block. # # a = (-5..5).to_a # a.uniq_by!{ |i| i*i } # a #=> [-5, -4, -3, -2, -1, 0] # # As can be seen in the example, order is significant. def uniq_by! #:yield: h = {} replace( inject([]){|a,x| h[yield(x)] ||= a << x} ) end end facets-2.9.3/lib/core/facets/array/recurse.rb0000644000004100000410000000111311714455226021103 0ustar www-datawww-dataclass Array # Apply a block to array, and recursively apply that block # to each sub-array or +types+. # # arr = ["a", ["b", "c", nil], nil] # arr.recurse{ |a| a.compact! } # #=> ["a", ["b", "c"]] # def recurse(*types, &block) types = [self.class] if types.empty? a = inject([]) do |array, value| case value when *types array << value.recurse(*types, &block) else array << value end array end yield a end # In place form of #recurse. def recurse!(&block) replace(recurse(&block)) end end facets-2.9.3/lib/core/facets/array/indexable.rb0000644000004100000410000000102511714455226021370 0ustar www-datawww-datarequire 'facets/indexable' require 'facets/array/splice' class Array include Indexable # Alias for shift, which removes and returns # the first element in an array. # # a = ["a","y","z"] # a.first! #=> "a" # a #=> ["y","z"] # # CREDIT: Trans alias_method :first!, :shift # Alias for pop, which removes and returns # the last element in an array. # # a = [1,2,3] # a.last! #=> 3 # a #=> [1,2] # # CREDIT: Trans alias_method :last!, :pop end facets-2.9.3/lib/core/facets/array/permutation.rb0000644000004100000410000000131111714455226022002 0ustar www-datawww-dataclass Array unless method_defined?(:permutation) # 1.8.7+ # Permutation provids the possible orders of an enumerable. # Each is indexed by a permutation number. The maximum number of # arrangements is the factorial of the size of the array. # # [1,2].permutation(2).to_a #=> [[1,2], [2,1]] # # CREDIT: Shin-ichiro Hara def permutation(n=size) if size < n or n < 0 elsif n == 0 yield([]) else self[1..-1].permutation(n - 1) do |x| (0...n).each do |i| yield(x[0...i] + [first] + x[i..-1]) end end self[1..-1].permutation(n) do |x| yield(x) end end end end end facets-2.9.3/lib/core/facets/array/product.rb0000644000004100000410000000102511714455226021115 0ustar www-datawww-dataclass Array unless method_defined?(:product) # 1.8.7+ # Provides the cartesian product of two or more arrays. # # a = [1,2].product([4,5]) # a #=> [[1, 4],[1, 5],[2, 4],[2, 5]] # # CREDIT: Thomas Hafner def product(*enums) enums.unshift self result = [[]] while [] != enums t, result = result, [] b, *enums = enums t.each do |a| b.each do |n| result << a + [n] end end end result end end end facets-2.9.3/lib/core/facets/array/traverse.rb0000644000004100000410000000160411714455226021273 0ustar www-datawww-dataclass Array # Returns a new array created by traversing the array and its # sub-arrays, executing the given block on the elements. # # h = ["A", "B", ["X", "Y"]] # # g = h.traverse{ |e| e.downcase } # # g #=> ["a", "b", ["x", "y"]] # # This is the same as recursive.map and will # likely be deprecated in the future because of it. # # CREDIT: Trans def traverse(&block) if block_given? map do |e| if e.respond_to?(:to_ary) e.to_ary.traverse(&block) else block.call(e) end end else to_enum(:traverse) end end # Like #recursive_map, but will change the array in place. # # h = ["A", "B", ["X", "Y"]] # # h.traverse!{ |e| e.downcase } # # h #=> ["a", "b", ["x", "y"]] # # CREDIT: Trans def traverse!(&block) replace(traverse(&block)) end end facets-2.9.3/lib/core/facets/array/delete_unless.rb0000644000004100000410000000034211714455226022271 0ustar www-datawww-dataclass Array # Inverse of #delete_if. # # [1,2,3].delete_unless{ |x| x < 2 } # #=> [1] # # CREDIT: Daniel Schierbeck def delete_unless(&block) delete_if { |element| not block.call(element) } end end facets-2.9.3/lib/core/facets/array/entropy.rb0000644000004100000410000000171011714455226021136 0ustar www-datawww-datarequire 'facets/array/probability' class Array # Shannon's entropy for an array - returns the average # bits per symbol required to encode the array. # Lower values mean less "entropy" - i.e. less unique # information in the array. # # e = %w{ a b c d e e e }.entropy # # ("%.3f" % e) #=> "2.128" # # CREDIT: Derek def entropy arr = self probHash = arr.probability # -- h is the Shannon entropy of the array h = -1.to_f * probHash.keys.inject(0.to_f) do |sum, i| sum + (probHash[i] * (Math.log(probHash[i])/Math.log(2.to_f))) end h end # Returns the maximum possible Shannon entropy of the array # with given size assuming that it is an "order-0" source # (each element is selected independently of the next). # # CREDIT: Derek def ideal_entropy arr = self unitProb = 1.0.to_f / arr.size.to_f (-1.to_f * arr.size.to_f * unitProb * Math.log(unitProb)/Math.log(2.to_f)) end end facets-2.9.3/lib/core/facets/array/not_empty.rb0000644000004100000410000000021511714455226021453 0ustar www-datawww-dataclass Array # Not empty? # # [].not_empty? #=> false # [1,2].not_empty? #=> true def not_empty? !empty? end end facets-2.9.3/lib/core/facets/array/contains.rb0000644000004100000410000000012111714455226021247 0ustar www-datawww-dataclass Array # Alias for #include?. alias_method :contains?, :include? end facets-2.9.3/lib/core/facets/array/merge.rb0000644000004100000410000000043711714455226020542 0ustar www-datawww-dataclass Array # In place #merge. # # a = [1,2] # a.merge! [2,3] # a #=> [1,2,3] # # CREDIT: Trans def merge!( other ) self.replace(self.merge(other)) end # Alias for |. # # [1,2].merge([2,3]) #=> [1,2,3] # alias_method :merge, :| end facets-2.9.3/lib/core/facets/array/store.rb0000644000004100000410000000025511714455226020575 0ustar www-datawww-dataclass Array # Store a value at a given index. Store is an alias for #[]=. # # a = [] # a.store(1, "A") # a[1] #=> "A" # alias_method :store, :[]= end facets-2.9.3/lib/core/facets/array/peek.rb0000644000004100000410000000003411714455226020360 0ustar www-datawww-datarequire 'facets/array/pull' facets-2.9.3/lib/core/facets/array/extract_options.rb0000644000004100000410000000144311714455226022666 0ustar www-datawww-dataclass Hash # By default, only instances of Hash itself are extractable. # Subclasses of Hash may implement this method and return # true to declare themselves as extractable. If a Hash # is extractable, Array#extract_options! pops it from # the Array when it is the last element of the Array. def extractable_options? instance_of?(Hash) end end class Array # Extracts options from a set of arguments. Removes and returns the last # element in the array if it's a hash, otherwise returns a blank hash. # # def options(*args) # args.extract_options! # end # # options(1, 2) # => {} # options(1, 2, :a => :b) # => {:a=>:b} # def extract_options! if Hash === last && last.extractable_options? pop else {} end end end facets-2.9.3/lib/core/facets/array/duplicates.rb0000644000004100000410000000003711714455226021574 0ustar www-datawww-datarequire 'facets/array/nonuniq' facets-2.9.3/lib/core/facets/array/thru.rb0000644000004100000410000000003411714455226020416 0ustar www-datawww-datarequire 'facets/array/from' facets-2.9.3/lib/core/facets/array/poke.rb0000644000004100000410000000003411714455226020372 0ustar www-datawww-datarequire 'facets/array/pull' facets-2.9.3/lib/core/facets/array/commonality.rb0000644000004100000410000000200711714455226021771 0ustar www-datawww-dataclass Array # Returns all items that are equal in terms of the supplied block. # If no block is given objects are considered to be equal if they # return the same value for Object#hash and if obj1 == obj2. # # [1, 2, 2, 3, 4, 4].commonality #=> { 2 => [2, 2], 4 => [4, 4] } # # ["foo", "bar", "a"].commonality { |str| str.length } # #=> { 3 => ["foo", "bar"] } # # This can be useful, for instance, in determining all persons that share # their last name with another person ... # # persons.collisions { |person| person.last_name } # # CREDIT: Florian Gross def commonality(&block) had_no_block = !block block ||= lambda { |item| item } result = Hash.new { |hash, key| hash[key] = Array.new } each do |item| key = block.call(item) result[key] << item end result.reject! do |key, values| values.size <= 1 end # -- return had_no_block ? result.values.flatten : result return result end alias_method :collisions, :commonality end facets-2.9.3/lib/core/facets/array/delete_values.rb0000644000004100000410000000172411714455226022264 0ustar www-datawww-dataclass Array # Delete multiple values from array. # # a = [1,2,3,4] # a.delete_values(1,2) #=> [1,2] # a #=> [3,4] # # CREDIT: Trans def delete_values(*values) d = [] values.each{ |v| d << delete(v) } d end # Delete multiple values from array given # indexes or index range. # # a = [1,2,3,4] # a.delete_values_at(1,2) #=> [2,3] # a #=> [1,4] # a = [1,2,3,4] # a.delete_values_at(0..2) #=> [1,2,3] # a #=> [4] # # NOTE: It would be nice to see #delete_at incorporate this # funcitonaility. # # CREDIT: Trans def delete_values_at(*selectors) idx = [] selectors.each{ |i| case i when Range idx.concat( i.to_a ) else idx << i.to_i end } idx.uniq! dvals = values_at(*idx) idx = (0...size).to_a - idx self.replace( values_at(*idx) ) return dvals end end facets-2.9.3/lib/core/facets/array/delete.rb0000644000004100000410000000020011714455226020671 0ustar www-datawww-data# Here for backward compatability. To be deprecated. require 'facets/array/delete_unless' require 'facets/array/delete_values' facets-2.9.3/lib/core/facets/array/probability.rb0000644000004100000410000000142211714455226021756 0ustar www-datawww-dataclass Array # Generates a hash mapping each unique element in the array to the # relative frequency, i.e. the probablity, of it appearence. # # [:a, :b, :c, :c].probability #=> {:a=> 0.25, :b=>0.25, :c=>0.5} # # CREDIT: Brian Schröder def probability probs = Hash.new(0.0) size = 0.0 each do |e| probs[e] += 1.0 size += 1.0 end probs.keys.each{ |e| probs[e] /= size } probs end #-- # Old Definition ... # # def probability # arr = self.to_a # probHash = Hash.new # size = arr.size.to_f # arr.uniq.each do |i| # ct = arr.inject(0) do |mem,obj| # obj.eql?(i) ? (mem+1) : mem # end # probHash[i] = ct.to_f/size # end # probHash # end #++ end facets-2.9.3/lib/core/facets/array/mode.rb0000644000004100000410000000074511714455226020371 0ustar www-datawww-dataclass Array # In Statistics mode is the value that occurs most frequently # in a given set of data. This method returns an array in case # their is a tie. # # [:a, :b, :c, :b, :d].mode #=> [:b] # [:a, :b, :c, :b, :a].mode #=> [:a, :b] # # Returns an Array of most common elements. # # @author Robert Klemme def mode max = 0 c = Hash.new 0 each {|x| cc = c[x] += 1; max = cc if cc > max} c.select {|k,v| v == max}.map {|k,v| k} end end facets-2.9.3/lib/core/facets/array/pad.rb0000644000004100000410000000155211714455226020206 0ustar www-datawww-dataclass Array # Pad an array with a given value up to a given length. # # [0,1,2].pad(6,"a") #=> [0,1,2,"a","a","a"] # # If length is a negative number padding will be added # to the beginning of the array. # # [0,1,2].pad(-6,"a") #=> ["a","a","a",0,1,2] # # CREDIT: Richard Laugesen def pad(len, val=nil) return dup if self.size >= len.abs if len < 0 Array.new((len+size).abs,val) + self else self + Array.new(len-size,val) end end # Like #pad but changes the array in place. # # a = [0,1,2] # a.pad!(6,"x") # a #=> [0,1,2,"x","x","x"] # # CREDIT: Richard Laugesen def pad!(len, val=nil) return self if self.size >= len.abs if len < 0 replace Array.new((len+size).abs,val) + self else concat Array.new(len-size,val) end end end facets-2.9.3/lib/core/facets/array/collisions.rb0000644000004100000410000000004311714455226021612 0ustar www-datawww-datarequire 'facets/array/commonality' facets-2.9.3/lib/core/facets/array/each_value.rb0000644000004100000410000000020711714455226021532 0ustar www-datawww-dataclass Array # Alias for #each. The intention of this method # is to provide polymorphism with Hash. alias :each_value :each end facets-2.9.3/lib/core/facets/array/before.rb0000644000004100000410000000202611714455226020701 0ustar www-datawww-dataclass Array # Returns the value previous to the given value. The value previous # to the first is the last. Returns nil if the given value is not # in the array. # # Examples # # sequence = ['a', 'b', 'c'] # sequence.before('a') #=> 'c' # sequence.before('b') #=> 'a' # sequence.before('c') #=> 'b' # sequence.before('d') #=> nil # # CREDIT: Tyler Rick def before(value) return nil unless include? value self[(index(value).to_i - 1) % length] end # Returns the value after the given value. The value before the last # is the first. Returns nil if the given value is not in the array. # # Examples # # sequence = ['a', 'b', 'c'] # sequence.after('a') #=> 'b' # sequence.after('b') #=> 'c' # sequence.after('c') #=> 'a' # sequence.after('d') #=> nil # # CREDIT: Tyler Rick def after(value) return nil unless include? value self[(index(value).to_i + 1) % length] end end facets-2.9.3/lib/core/facets/array/combination.rb0000644000004100000410000000150211714455226021737 0ustar www-datawww-dataclass Array unless method_defined?(:combination) # 1.8.7+ require 'facets/enumerator' # Yields the block to each unique combination of _n_ elements. # # a = %w|a b c d| # a.combination(3) # # produces # # [["a", "b", "c"], # ["a", "b", "d"], # ["a", "c", "d"], # ["b", "c", "d"]] # # CREDIT: Florian Gross def combination(k=2) if block_given? s = to_a n = s.size return unless (1..n) === k idx = (0...k).to_a loop do yield s.values_at(*idx) i = k - 1 i -= 1 while idx[i] == n - k + i break if i < 0 idx[i] += 1 (i + 1 ... k).each {|j| idx[j] = idx[i] + j - i} end else to_enum(:combination, k) end end end end facets-2.9.3/lib/core/facets/array/op_pow.rb0000644000004100000410000000047311714455226020746 0ustar www-datawww-datarequire 'facets/array/product' class Array # Array#** is an alias for Array#product. # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # @uncommon # require 'facets/array/op_pow' # alias_method :**, :product end facets-2.9.3/lib/core/facets/array/rotate.rb0000644000004100000410000000167211714455226020743 0ustar www-datawww-dataclass Array unless method_defined?(:rotate) # Rotates an array's elements from back to front n times. # # [1,2,3].rotate #=> [2,3,1] # [2,3,1].rotate #=> [3,1,2] # [3,1,2].rotate #=> [1,2,3] # # [1,2,3].rotate(3) #=> [1,2,3] # # A negative parameter reverses the order from front to back. # # [1,2,3].rotate(-1) #=> [3,1,2] # # CREDIT: Florian Gross, Thomas Sawyer def rotate(n=1) self.dup.rotate!(n) end end unless method_defined?(:rotate!) # Same as #rotate, but acts in place. # # a = [1,2,3] # a.rotate! # a #=> [2,3,1] # # CREDIT: Florian Gross, Thomas Sawyer def rotate!(n=1) n = n.to_int return self if (n == 0 or self.empty?) if n < 0 n.abs.times{ self.unshift( self.pop ) } else n.abs.times{ self.push( self.shift ) } end self end end end facets-2.9.3/lib/core/facets/array/splice.rb0000644000004100000410000000075011714455226020720 0ustar www-datawww-datarequire 'facets/array/store' class Array # Splice acts a combination of #slice! and #store. # If two arguments are given it calls #store. # If a single argument is given it calls slice!. # # a = [1,2,3] # a.splice(1) #=> 2 # a #=> [1,3] # # a = [1,2,3] # a.splice(1,4) #=> 4 # a #=>[1,4,3] # # CREDIT: Trans def splice(*args) if args.size == 1 slice!(*args) else store(*args) end end end facets-2.9.3/lib/core/facets/array/occurent.rb0000644000004100000410000000003711714455226021261 0ustar www-datawww-datarequire 'facets/array/nonuniq' facets-2.9.3/lib/core/facets/array/from.rb0000644000004100000410000000120611714455226020401 0ustar www-datawww-dataclass Array # Returns last _n_ elements. # # %w{W o r l d}.from(3) #=> %w{l d} # def from(i) return self if i >= size self[i, size - i] end unless method_defined?(:from) # Fetch values from a start index thru an end index. # # [1,2,3,4,5].thru(0,2) #=> [1,2,3] # [1,2,3,4,5].thru(2,4) #=> [3,4,5] # # [1,2,3,4,5].thru(2) #=> [1,2,3] # [1,2,3,4,5].thru(4) #=> [1,2,3,4,5] # def thru(from, to=nil) from, to = 0, from unless to to = size - 1 if to >= size a = [] i = from while i <= to a << self[i] i += 1 end a end unless method_defined?(:thru) end facets-2.9.3/lib/core/facets/array/only.rb0000644000004100000410000000067211714455226020425 0ustar www-datawww-dataclass Array # Returns the _only_ element in the array. Raises an IndexError if # the array's size is not 1. # # [5].only # => 5 # # expect IndexError do # [1,2,3].only # end # # expect IndexError do # [].only # end # # CREDIT: Gavin Sinclair, Noah Gibbs def only unless size == 1 raise IndexError, "Array#only called on non-single-element array" end first end end facets-2.9.3/lib/core/facets/array/nonuniq.rb0000644000004100000410000000250311714455226021126 0ustar www-datawww-dataclass Array # Returns a list of non-unique elements # # [1,1,2,2,3,4,5].nonuniq #=> [1,2] # # @author Martin DeMello def nonuniq h1 = {} h2 = {} each {|i| h2[i] = true if h1[i] h1[i] = true } h2.keys end # Same as `#nonuniq` but acting in place. def nonuniq! h1 = {} h2 = {} each {|i| h2[i] = true if h1[i] h1[i] = true } self.replace(h2.keys) end # Return list of duplictate elements. # # @param [Integer] min # The minimum number of duplicatation necessary for inclusion. # # @author Rebort Dober (current implementation) # @author Thibaut Barrère def duplicates(min=2) h = Hash.new( 0 ) each {|i| h[i] += 1 } h.delete_if{|_,v| v < min}.keys end # Returns a list of elements that occur +n+ times. # # [0,1,1,1,3,0,1,2,4].occurent(3) #=> [1] # # If +n+ is a Range then returns elements that occur a number # of time within the range. # # [0,1,1,1,3,0,1,2,4].occurent(2..4) #=> [0,1] # # @author Robert Dober def occurent(n=2) h = Hash.new( 0 ) each do |i| h[i] += 1 end case n when nil h.delete_if{ |_,v| ! yield(v) }.keys when Range h.delete_if{ |_,v| ! n.include?(v) }.keys else h.delete_if{|_,v| v != n}.keys end end end facets-2.9.3/lib/core/facets/array/split.rb0000644000004100000410000000072411714455226020575 0ustar www-datawww-dataclass Array # Split on matching pattern. Unlike #divide this does not include matching elements. # # ['a1','a2','b1','a3','b2','a4'].split(/^b/) # #=> [['a1','a2'],['a3'],['a4']] # # CREDIT: Trans def split(pattern) memo = [] sect = [] each do |obj| if pattern === obj memo << sect sect = [] else sect << obj end end memo << sect memo.pop while memo.last == [] memo end end facets-2.9.3/lib/core/facets/array/index.rb0000644000004100000410000000064111714455226020547 0ustar www-datawww-dataclass Array if RUBY_VERSION < '1.8.7' alias_method :_facets_index, :index # Allows #index to accept a block. # # ['a', 'b', 'c'].index{ |x| x.upcase == 'C' } #=> 2 # # IMPORTANT: This is one of the few core overrides in Facets. def index(obj=nil, &block) if block_given? _facets_index(find(&block)) else _facets_index(obj) end end end end facets-2.9.3/lib/core/facets/array/pull.rb0000644000004100000410000000122211714455226020410 0ustar www-datawww-dataclass Array # Alias for shift which removes an object off first slot of an array. # This is the opposite of pop. alias_method :pull, :shift # Peek at the top of the stack (the end of the array). # # a = [1, 2, 3] # a.peek #=> 3 # a #=> [1, 2, 3] # # Or provide an index to inspect the array from back to front. def peek(i=0) i = -(i + 1) fetch(i) end # Put an object on the bottom of the stack (front of the array). # # a = [2, 3] # a.poke(1) # a #=> [1, 2, 3] # # Or supply an index and #poke works like #insert. def poke(x, i=0) insert(i,x) end end facets-2.9.3/lib/core/facets/array/collapse.rb0000644000004100000410000000026311714455226021242 0ustar www-datawww-dataclass Array # Simplify an array by flattening it then compacting it. # # [1,[2,nil,[3]],nil,4].collapse #=> [1,2,3,4] # def collapse flatten.compact end end facets-2.9.3/lib/core/facets/array/conjoin.rb0000644000004100000410000000435711714455226021107 0ustar www-datawww-dataclass Array # This is more advanced form of #join. It allows for fine control # of separators. # # NOTE: The old version used to default its separator to ", " and # default the terminating separator to " and ". This is no longer # the case. You must specifically provide these parameters. # # If no paramters are given, it acts like #join but will a space # separator. # # [1,2,3].conjoin # #=> "1 2 3" # # Use comma+space and 'and' on tail. # # [1,2,3].conjoin(', ', ' and ') # #=> "1, 2 and 3" # # Use comma+space and 'or' on tail using :last option. # # [1,2,3].conjoin(', ', :last => ' or ') # #=> "1, 2 or 3" # # Use semicolon+space and ampersand on tail using index. # # [1,2,3].conjoin('; ', -1 => ' & ') # #=> "1; 2 & 3" # # Can take a block to determine separator. # # [1,2,3,4].conjoin{ |i, a, b| i % 2 == 0 ? '.' : '-' } # #=> "1.2-3.4" # # This makes very esoteric transformation possible. # # [1,1,2,2].conjoin{ |i, a, b| a == b ? '=' : ' != ' } # #=> "1=1 != 2=2" # # [1,2,3,4].conjoin{ |i, x, y| "<#{i} #{x} #{y}>" } # #=> "1<0 1 2>2<1 2 3>3<2 3 4>4" # # There are also spacing options. Providing the :space option # pads the separators. # # [1,2,3].conjoin(',', '&', :space=>2) # #=> "1 , 2 & 3" # # And the :spacer option can set an alternate spacing string. # # [1,2,3].conjoin('|', '>', :space=>2, :spacer=>'-') # #=> "1--|--2-->--3" # # CREDIT: Trans def conjoin(*args, &block) return first.to_s if size < 2 options = (Hash===args.last) ? args.pop : {} spacing = options.delete(:space) || 0 spacer = options.delete(:spacer) || " " space = spacer * spacing.to_i sep = [] if block_given? (size - 1).times do |i| sep << space + yield(i, *slice(i,2)) + space end else separator = args.shift || " " options[-1] = args.shift if args.first options[0] = options.delete(:first) if options.key?(:first) options[-1] = options.delete(:last) if options.key?(:last) separator = space + separator + space sep = [separator] * (size - 1) options.each{|i, s| sep[i] = space + s + space} end zip(sep).join end end facets-2.9.3/lib/core/facets/array/after.rb0000644000004100000410000000003611714455226020537 0ustar www-datawww-datarequire 'facets/array/before' facets-2.9.3/lib/core/facets/enumerable/0000755000004100000410000000000011714455226020113 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/enumerable/one.rb0000644000004100000410000000174711714455226021232 0ustar www-datawww-datamodule Enumerable unless method_defined?(:one?) # 1.8.7+ # Enumerable#one? returns +true+ if and only if exactly one # element in the collection satisfies the given predicate. # # If no predicate is provided, Enumerable#one? returns +true+ if # and only if exactly one element has a true value # (i.e. not +nil+ or +false+). # # [].one? # => false # [nil].one? # => false # [5].one? # => true # [5,8,9].one? # => false # (1...10).one? { |n| n == 5 } # => true # (1...10).one? { |n| n < 5 } # => false # # CREDIT: Gavin Sinclair def one? # :yield: e matches = 0 if block_given? self.each do |e| if yield(e) matches += 1 return false if matches > 1 end end return (matches == 1) else one? { |e| e } end end end end facets-2.9.3/lib/core/facets/enumerable/collect_with_index.rb0000644000004100000410000000005411714455226024306 0ustar www-datawww-datarequire 'facets/enumerable/map_with_index' facets-2.9.3/lib/core/facets/enumerable/recursively.rb0000644000004100000410000000340711714455226023020 0ustar www-datawww-datamodule Enumerable # Returns a recursive functor, that allows enumerable methods to iterate # through enumerable sub-elements. By default it only recurses over # elements of the same type. # def recursively(*types, &block) Recursor.new(self, *types, &block) end # Recursor is a specialized Functor for recurively iterating over Enumerables. #-- # TODO: Return Enumerator if no +yld+ block is given. # # TODO: Add limiting +depth+ option to Enumerable#recursively ? #++ class Recursor instance_methods(true).each{ |m| private m unless /^(__|object_id$)/ =~ m.to_s } def initialize(enum, *types, &block) @enum = enum @types = types.empty? ? [@enum.class] : types @block = block end def method_missing(op, &yld) rec = @block || lambda{ |v| v } yld = yld || lambda{ |v| v } # ? to_enum @enum.__send__(op) do |v| case v when String # b/c of 1.8 yld.call(v) when *@types res = v.recursively(*@types, &@block).__send__(op,&yld) rec.call(res) else yld.call(v) end end end end ## TODO: When no longer needing to support 1.8.6 we could get rid of ## the Recursor class and use: ## # ## def recursively(*types, &block) ## types = types.empty? ? [self.class] : types ## Functor.new do |op, &yld| ## rec = block || lambda{ |v| v } ## yld = yld || lambda{ |v| v } # ? to_enum ## __send__(op) do |v| ## case v ## when String # b/c of 1.8 ## yld.call(v) ## when *types ## res = v.recursively(*types, &block).__send__(op,&yld) ## rec.call(res) ## else ## yld.call(v) ## end ## end ## end ## end end facets-2.9.3/lib/core/facets/enumerable/filter.rb0000644000004100000410000000155411714455226021732 0ustar www-datawww-datamodule Enumerable # The block acts as an arbitrary filter on the data. Unlike map, # it can choose to drop elements from the result and/or add # additional elements. The first object passed to the block is # the receiver of the output. # # x = (1..10000) # x = x.filter{ |out,i| out << i if i % 2 == 0 } # like select # x = x.filter{ |out,i| out << i + 100 } # like map # x = x.take(3) # # x #=> [102, 104, 106] # # This is very similar to #each_with_object, but #filter handles # argument better by reversing their order and using the splat # operator. (This was also once known as #injecting.) # # CREDIT: David Black, Louis J Scoras def filter(output=[]) #:yeild: if block_given? each do |*input| yield(output, *input) end output else to_enum(:filter) end end end facets-2.9.3/lib/core/facets/enumerable/uniq_by.rb0000644000004100000410000000037611714455226022114 0ustar www-datawww-datamodule Enumerable # Like #uniq, but determines uniqueness based on a given block. # # (-5..5).to_a.uniq_by {|i| i*i } # #=> [-5, -4, -3, -2, -1, 0] # def uniq_by #:yield: h = {}; inject([]) {|a,x| h[yield(x)] ||= a << x} end end facets-2.9.3/lib/core/facets/enumerable/sum.rb0000644000004100000410000000051511714455226021245 0ustar www-datawww-datamodule Enumerable # Uses #+ to sum the enumerated elements. # # [1,2,3].sum #=> 6 # [3,3,3].sum #=> 9 # # @author Dawid Marcin Grzesiak (bug fix) def sum(identity=0, &block) if block_given? map(&block).sum(identity) else inject{ |sum, element| sum + element } || identity end end end facets-2.9.3/lib/core/facets/enumerable/visit.rb0000644000004100000410000000110011714455226021566 0ustar www-datawww-datamodule Enumerable # Recursively iterate over all Enumerable elements, or # subset given :type=>[type1, type2, ...]. # # [1, 2, 8..9].visit{ |x| x.succ } # # => [2, 3, [9, 10]] # def visit(opts={}, &block) type = opts[:type] ? [opts[:type]].flatten : [Enumerable] skip = opts[:skip] map do |v| case v when String # b/c of 1.8 block.call(v) when *type v.visit(opts, &block) else if skip && Enumerable === v v else block.call(v) end end end end end facets-2.9.3/lib/core/facets/enumerable/find_yield.rb0000644000004100000410000000201411714455226022543 0ustar www-datawww-datamodule Enumerable # Yield each element to the block and return the result # of the block when that result evaluates as true, # terminating early like #detect and #find. # # obj1 = Object.new # obj2 = Object.new # # def obj1.foo?; false; end # def obj2.foo?; true ; end # # def obj1.foo ; "foo1"; end # def obj2.foo ; "foo2"; end # # [obj1, obj2].find_yield{ |obj| obj.foo if obj.foo? } #=> "foo2" # # Another example. # # [1,2,3,4,5].find_yield{ |i| j = i+1; j if j % 4 == 0 } #=> 4 # # If the block is never true, return the object given in the first parameter, # or nil if none specified. # # [1,2,3].find_yield{ |_| false } #=> nil # [false].find_yield(1){ |_| false } #=> 1 # def find_yield(fallback=nil) #:yield: each do |member| result = yield(member) return result if result end fallback end # Alias for #find_yield. # # DEPRECATE: This has been renamed to #find_yield. alias_method :map_detect, :find_yield end facets-2.9.3/lib/core/facets/enumerable/take.rb0000644000004100000410000000036411714455226021367 0ustar www-datawww-datamodule Enumerable # Return the first n items from the collection # def take(n) res = [] count = 0 each do |e| break if count >= n res << e count += 1 end res end unless method_defined?(:take) end facets-2.9.3/lib/core/facets/enumerable/each_by.rb0000644000004100000410000000132711714455226022035 0ustar www-datawww-datarequire 'facets/enumerator' module Enumerable # Iterate through slices. If slice +steps+ is not # given, the arity of the block is used. # # x = [] # [1,2,3,4].each_by{ |a,b| x << [a,b] } # x #=> [ [1,2], [3,4] ] # # x = [] # [1,2,3,4,5,6].each_by(3){ |a| x << a } # x #=> [ [1,2,3], [4,5,6] ] # # This is just like each_slice, except that it will check # the arity of the block. If each_slice ever suppots this # this method can be deprecated. # # CREDIT: Trans def each_by(steps=nil, &block) if steps each_slice(steps, &block) else steps = block.arity.abs each_slice(steps, &block) #each_slice(steps) {|i| block.call(*i)} end end end facets-2.9.3/lib/core/facets/enumerable/zip_map.rb0000644000004100000410000000004511714455226022076 0ustar www-datawww-datarequire 'facets/enumerable/map_with' facets-2.9.3/lib/core/facets/enumerable/map_with_index.rb0000644000004100000410000000056611714455226023446 0ustar www-datawww-datamodule Enumerable # Same as #collect but with an iteration counter. # # a = [1,2,3].collect_with_index { |e,i| e*i } # a #=> [0,2,6] # # CREDIT: Gavin Sinclair def map_with_index r = [] each_with_index do |e, i| r << yield(e, i) end r end # Alias for map_with_index. alias_method :collect_with_index, :map_with_index end facets-2.9.3/lib/core/facets/enumerable/none.rb0000644000004100000410000000154011714455226021377 0ustar www-datawww-datamodule Enumerable unless method_defined?(:none?) # 1.8.7+ # Enumerable#none? is the logical opposite of the builtin method # Enumerable#any?. It returns +true+ if and only if _none_ of # the elements in the collection satisfy the predicate. # # If no predicate is provided, Enumerable#none? returns +true+ # if and only if _none_ of the elements have a true value # (i.e. not +nil+ or +false+). # # [].none? # => true # [nil].none? # => true # [5,8,9].none? # => false # (1...10).none? { |n| n < 0 } # => true # (1...10).none? { |n| n > 0 } # => false # # CREDIT: Gavin Sinclair def none? # :yield: e if block_given? not self.any? { |e| yield e } else not self.any? end end end end facets-2.9.3/lib/core/facets/enumerable/count.rb0000644000004100000410000000202411714455226021566 0ustar www-datawww-datarequire 'facets/hash/count' module Enumerable # Count the number of items in an enumerable equal (==) # to the given object(s). # # e = [ 'a', 1, 'a' ] # # e.count(1) #=> 1 # e.count('a') #=> 2 # # The method can count more than one item by supplying additional # arguments. # # e.count('a', 1) #=> 3 # # A block may also be used to select countable entries. # # e.count{ |x| String === x } #=> 2 # # Note that Hash#count only considers values. # # e = { 'a' => 2, 'x' => 2, 'b' => 1 } # # e.count(1) #=> 1 # e.count(2) #=> 2 # # NOTE: This is one of the few method overrides in Facets. # # CREDIT: Trans def count(*items, &block) if block || !items.empty? r = self r = r.select(&block) if block r = r.select{ |x| items.any?{ |i| i == x } } if !items.empty? r.size else begin size rescue i=0; each{ |e| i+=1 }; i end end end end class Array remove_method(:count) rescue nil end facets-2.9.3/lib/core/facets/enumerable/incase.rb0000644000004100000410000000077411714455226021712 0ustar www-datawww-datamodule Enumerable # The same as #include? but tested using #=== instead of #==. # # [1, 2, "a"].incase?(2) #=> true # [1, 2, "a"].incase?(String) #=> true # [1, 2, "a"].incase?(3) #=> false # # Why the name `incase`? Because the method uses case-equality. # Along with the alliteration for "in case" and the similarity # with "include?", it seemed like the perfect fit. # # @author Lavir the Whiolet # def incase?(what) any? { |x| what === x } end end facets-2.9.3/lib/core/facets/enumerable/hashify.rb0000644000004100000410000000146411714455226022100 0ustar www-datawww-datamodule Enumerable # Create a hash whose keys are the enumerable's elements, with specified # values. # # If no block is given, the given parameter (default true) is used for # all values, e.g.: # # [1,2,3,4].hashify #=> {1=>true, 2=>true, 3=>true, 4=>true} # [1,2,3,4].hashify("a") #=> {1=>"a", 2=>"a", 3=>"a", 4=>"a"} # # If a block is given, each key's value is the result of running the # block for that key, e.g.: # # [1,2,3,4].hashify{|n| "a" * n} #=> {1=>"a", 2=>"aa", 3=>"aaa", 4=>"aaaa"} # # @author Ronen Barzel # # @uncommon # require 'facets/enumerable/hashify' # def hashify(val=true) h = {} if block_given? each { |item| h[item] = yield(item) } else each { |item| h[item] = val } end h end end facets-2.9.3/lib/core/facets/enumerable/map_detect.rb0000644000004100000410000000004711714455226022546 0ustar www-datawww-datarequire 'facets/enumerable/find_yield' facets-2.9.3/lib/core/facets/enumerable/purge.rb0000644000004100000410000000200111714455226021553 0ustar www-datawww-datamodule Enumerable # A versitle compaction method. Like #map but used # to filter out multiple items in a single step. # # Without +trash+ arguments +nil+ is assumed. # # [1, nil, 2].purge #=> [1,2] # # If +trash+ arguments are given, each argument is # compared for a match using #==. # # (1..6).purge(3,4) #=> [1,2,5,6] # # If a block is given, the yield is used in the # matching condition instead of the element itsef. # # (1..6).purge(0){ |n| n % 2 } #=> [1,3,5] # # NOTE: This could just as well be an override of the # core #compact method, but to avoid potential issues # associated with overriding core methods we use the # alternate name #purge. # # CREDIT: Trans def purge(*trash, &block) trash = [nil] if trash.empty? r = [] if block_given? each do |e| y = yield(e) r << e unless trash.any?{|t| t == y} end else each do |e| r << e unless trash.any?{|t| t == e} end end r end end facets-2.9.3/lib/core/facets/enumerable/cluster_by.rb0000644000004100000410000000061011714455226022610 0ustar www-datawww-datarequire 'facets/enumerable/group_by' module Enumerable # Similar to #group_by but returns an array of the groups. # Returned elements are sorted by block. # # %w{this is a test}.cluster_by {|x| x[0]} # #=> [ ['a'], ['is'], ['this', 'test'] ] # # CREDIT: Erik Veenstra def cluster_by(&b) group_by(&b).sort.transpose.pop || [] # group_by(&b).values ? end end facets-2.9.3/lib/core/facets/enumerable/map_with.rb0000644000004100000410000000057011714455226022252 0ustar www-datawww-datamodule Enumerable # Combines #zip and #map in a single efficient operation. # # h = {} # [1,2,3].map_with [:x,:y,:z] do |n,k| # h[k] = n # end # h #=> {:x=>1, :y=>2, :z=>3} # # @return [Hash] # # @author Michael Kohl def map_with(*arrays, &block) enum_for(:zip, *arrays).map(&block) end # alias_method :zip_map, :map_with end facets-2.9.3/lib/core/facets/enumerable/group_by.rb0000644000004100000410000000150511714455226022267 0ustar www-datawww-datamodule Enumerable unless method_defined?(:group_by) # 1.9 # Enumerable#group_by is used to group items in a collection by something # they have in common. The common factor is the key in the resulting hash, # the array of like elements is the value. # # (1..5).group_by { |n| n % 3 } # #=> { 0 => [3], 1 => [1, 4], 2 => [2,5] } # # Applied to an array. # # ["I had", 1, "dollar and", 50, "cents"].group_by { |e| e.class } # #=> { String => ["I had","dollar and","cents"], Fixnum => [1,50] } # # Applied to a hash: # # {:a=>1, :b=>2, :c=>1}.group_by{ |k,v| v } # #=> { 1=>[[:c,1], [:a,1]], 2=>[[:b,2]] } # # CREDIT: Erik Veenstra def group_by #:yield: r = Hash.new each{ |e| (r[yield(e)] ||= []) << e } r end end end facets-2.9.3/lib/core/facets/enumerable/accumulate.rb0000644000004100000410000000360111714455226022563 0ustar www-datawww-datarequire 'facets/functor' module Enumerable # Accumulate a set of a set. For example, in an ORM design # where `Group has_many User` we might have something # equivalent to the following. # # Group = Struct.new(:users) # User = Struct.new(:name, :friends) # # user1 = User.new('John', []) # user2 = User.new('Jane', ['Jill']) # user3 = User.new('Joe' , ['Jack', 'Jim']) # # group1 = Group.new([user1, user2]) # group2 = Group.new([user2, user3]) # # groups = [group1, group2] # # Now we can *accumulate* the users of all groups. # # groups.accumulate.users #=> [user1, user2, user3] # # You may pass an argument to perform chains, e.g. the following # returns the names of users from all groups. # # groups.accumulate(2).users.name #=> ['John','Jane','Joe'] # # Or we can gather all the friends of all users in groups. # # groups.accumulate(2).users.friends #=> ['Jill','Jack','Jim'] # # This is more convenient then the equivalent. # # groups.accumulate.users.accumulate.friends #=> ['Jill','Jack','Jim'] # # CREDIT: George Moshchovitis, Daniel Emirikol def accumulate(iterations=1) return self if iterations == 0 Functor.new do |op, *args| #result = inject([]) { |a, x| a << x.send(op, *args) }.flatten.uniq result = [] each { |x| result << x.send(op, *args) } result.flatten.uniq.accumulate(iterations - 1) end end # Same as #accumulate, but does not apply #uniq to final result. # # groups.accumulate_all(2).users.friends #=> ['Jill', 'Jill','Jack','Jim'] # def accumulate_all(iterations=1) return self if iterations == 0 Functor.new do |op, *args| #result = inject([]) { |a, x| a << x.send(op, *args) }.flatten result = [] each { |x| result << x.send(op, *args) } result.flatten.accumulate_all(iterations - 1) end end end facets-2.9.3/lib/core/facets/enumerable/ewise.rb0000644000004100000410000000262311714455226021557 0ustar www-datawww-datarequire 'facets/functor' module Enumerable # Returns an elementwise Functor designed to make R-like # elementwise operations possible. This is very much like # the #every method, but it treats array argument specially. # # ([1,2].ewise + 3) #=> [4,5] # # Vector to vector # # ([1,2].ewise + [4,5]) #=> [5,7] # # Special thanks to Martin DeMello for helping to develop this. def ewise(count=1) Functor.new do |op,*args| if args.empty? r = self count.times do r = r.collect{ |a| a.send(op) } end r else r = args.collect do |arg| if Array === arg #arg.kind_of?(Enumerable) x = self count.times do ln = (arg.length > length ? length : arg.length ) x = x.slice(0...ln) x = x.zip(arg[0...ln]) x = x.collect{ |a,b| a.send(op,b) } #x = x.collect{ |a,b| b ? a.send(op,b) : nil } end x else x = self count.times do x = x.collect{ |a| a.send(op,arg) } end x end end r.flatten! if args.length == 1 r end end end # Long-term for #ewise. # # a = [1,2] # (a.elementwise + 3) #=> [4,5] # (a.elementwise + [4,5]) #=> [5,7] # alias_method :elementwise, :ewise end facets-2.9.3/lib/core/facets/enumerable/per.rb0000644000004100000410000000414511714455226021232 0ustar www-datawww-datarequire 'facets/functor' #-- # TODO: Consider Enumerator methods. #++ module Enumerable # Per element meta-functor. # # ([1,2,3].per(:map) + 3) #=> [4,5,6] # ([1,2,3].per(:select) > 1) #=> [2,3] # # Using fluid notation. # # ([1,2,3].per.map + 3) #=> [4,5,6] # ([1,2,3].per.select > 1) #=> [2,3] # def per(enum_method=nil, *enum_args) if enum_method Permeator.new(self, enum_method, *enum_args) else Functor.new do |enumr_method, *enumr_args| Permeator.new(self, enumr_method, *enumr_args) end end end # Permeator is a Functor for operating over each element of an Enumearble. # (Note: This used to be called an Elementor.) # # TODO: With Ruby 1.9+ this would not be required, as it can be replaced # by a generic Functor, becuase then lambda definitions can pass blocks. # class Permeator #:nodoc: private(*instance_methods.select{|x| x !~ /^__/ }) def initialize(enum_object, enum_method=nil, *enum_args) @enum_object = enum_object @enum_method = enum_method || :map @enum_args = enum_args end def instance_delegate @enum_object end def instance_operator @enum_method end def method_missing(sym, *args, &blk) @enum_object.__send__(@enum_method){ |x| x.__send__(sym, *args, &blk) } end end ## TODO: Use this when 1.8.6 support is not longer needed. =begin # Per element meta-functor. # # ([1,2,3].per(:map) + 3) #=> [4,5,6] # ([1,2,3].per(:select) > 1) #=> [2,3] # # Using fluid notation. # # ([1,2,3].per.map + 3) #=> [4,5,6] # ([1,2,3].per.select > 1) #=> [2,3] # def per(enum_method=nil, *enum_args) if enum_method Functor.new do |op, *args, &blk| __send__(enum_method, *enum_args){ |x| x.__send__(op, *args, &blk) } end else Functor.new do |enumr_method, *enumr_args| Functor.new do |op, *args, &blk| __send__(enumr_method, *enumr_args){ |x| x.__send__(op, *args, &blk) } end end end end =end end facets-2.9.3/lib/core/facets/enumerable/mash.rb0000644000004100000410000000004211714455226021364 0ustar www-datawww-datarequire 'facets/enumerable/graph' facets-2.9.3/lib/core/facets/enumerable/every.rb0000644000004100000410000000127511714455226021577 0ustar www-datawww-datarequire 'facets/enumerable/per' module Enumerable # Returns an elemental object. This allows # you to map a method on to every element. # # r = [1,2,3].every + 3 # r #=> [4,5,6] # def every per(:map) end # In place version of #every. # def every! raise NoMethodError unless respond_to?(:map!) per(:map!) end #-- # These used to be defined via Functors as follows ... # # def every # Functor.new do |op,*args| # map{ |a| a.send(op,*args) } # end # end # # def every! # raise NoMethodError unless respond_to?(:map!) # Functor.new do |op,*args| # map!{ |a| a.send(op,*args) } # end # end #++ end facets-2.9.3/lib/core/facets/enumerable/frequency.rb0000644000004100000410000000074011714455226022442 0ustar www-datawww-datamodule Enumerable # Generates a hash mapping each unique symbol in the array # to the absolute frequency it appears. # # [:a,:a,:b,:c,:c,:c].frequency #=> {:a=>2,:b=>1,:c=>3} # # CREDIT: Brian Schröder # #-- # NOTE: So why not use #inject here? e.g. ... # # inject(Hash.new(0)){|p,v| p[v]+=1; p} # # Because it is a fair bit slower than the traditional definition. #++ def frequency p = Hash.new(0); each{ |v| p[v] += 1 }; p end end facets-2.9.3/lib/core/facets/enumerable/map_by.rb0000644000004100000410000000141311714455226021706 0ustar www-datawww-datamodule Enumerable # Like #group_by, but maps the second value returned from the block. # # a = [1,2,3,4,5] # a.map_by{ |e| [e % 2, e + 1] } # #=> { 0=>[3,5], 1=>[2,4,6] } # # Works well with a hash too. # # h = {"A"=>1, "B"=>1, "C"=>1, "D"=>2, "E"=>2} # h.map_by{ |k,v| [v, k.downcase] } # #=> {1=>["a", "b", "c"], 2=>["d", "e"]} # # If a second value is not returned, #map_by acts like #group_by. # # h = {"A"=>1, "B"=>1, "C"=>1, "D"=>2, "E"=>2} # h.map_by{ |k,v| v } # #=> {1=>[["A",1], ["B",1], ["C",1]], 2=>[["D",2], ["E",2]]} # def map_by #:yield: res = {} each do |a| k,v = yield(*a) if v (res[k] ||= []) << v else (res[k] ||= []) << a end end res end end facets-2.9.3/lib/core/facets/enumerable/expand.rb0000644000004100000410000000035211714455226021717 0ustar www-datawww-datamodule Enumerable # Expand all elements of an Enumerable object. # # [0, 2..3, 5..7].expand #=> [0,[2, 3],[5,6,7]] # # CREDIT: Trans def expand map do |x| (Enumerable === x ? x.expand : x) end end end facets-2.9.3/lib/core/facets/enumerable/defer.rb0000644000004100000410000000267611714455226021540 0ustar www-datawww-datarequire 'facets/denumerable' module Enumerable # Without a block: wrap the Enumerable object in such a way that map, # select and similar operations are performed "horizontally" across a # series of blocks, instead of building an array of results at each step. # This reduces memory usage, allows partial results to be provided # early, and permits working with infinite series. # # a = (1..1_000_000_000).defer.select{ |i| i % 2 == 0 }. # map{ |i| i + 100 }. # take(10).to_a # # With a block: the block acts as an arbitrary filter on the data. Unlike # map, it can choose to drop elements from the result, and/or add # additional ones. The first object passed to the block is the receiver # of the output. # # (1..1_000_000_000). # defer { |out,i| out << i if i % 2 == 0 }. # like select # defer { |out,i| out << i + 100 }. # like map # take(10).to_a # # Use a method like to_a or to_h at the end of the chain when you want an # Array or Hash built with the results, or each{...} if you just want # to output each result and discard it. # def defer(&blk) if block_given? Denumerator.new do |output| each do |*input| yield(output, *input) end end else Denumerator.new do |output| each do |*input| output.yield(*input) end end end end end facets-2.9.3/lib/core/facets/enumerable/modulate.rb0000644000004100000410000000066611714455226022262 0ustar www-datawww-datamodule Enumerable # Divide an array into groups by modulo of the index. # # [2,4,6,8].modulate(2) #=> [[2,6],[4,8]] # # CREDIT: Trans # # NOTE: Would the better name for this be 'collate'? def modulate(modulo) return to_a if modulo == 1 raise ArgumentError, 'bad modulo' if size % modulo != 0 r = Array.new(modulo, []) (0...size).each do |i| r[i % modulo] += [self[i]] end r end end facets-2.9.3/lib/core/facets/enumerable/graph.rb0000644000004100000410000000144511714455226021545 0ustar www-datawww-datamodule Enumerable # Like `#map`/`#collect`, but generates a Hash. The block is expected # to return two values: the key and the value for the new hash. # # numbers = (1..3) # squares = numbers.graph{ |n| [n, n*n] } # { 1=>1, 2=>4, 3=>9 } # sq_roots = numbers.graph{ |n| [n*n, n] } # { 1=>1, 4=>2, 9=>3 } # # CREDIT: Andrew Dudzik (adudzik), Trans def graph(&yld) if yld h = {} each do |*kv| r = yld[*kv] case r when Hash nk, nv = *r.to_a[0] when Range nk, nv = r.first, r.last else nk, nv = *r end h[nk] = nv end h else Enumerator.new(self,:graph) end end # Alias for #graph, which stands for "map hash". alias_method :mash, :graph end facets-2.9.3/lib/core/facets/enumerable/map_send.rb0000644000004100000410000000074111714455226022230 0ustar www-datawww-datamodule Enumerable # Send a message to each element and collect the result. # # [1,2,3].map_send(:+, 3) #=> [4,5,6] # # CREDIT: Sean O'Halpin def map_send(meth, *args, &block) map{|e| e.send(meth, *args, &block)} end #-- # Old defintion confused me ... # # def map_send(meth, *args) #:yield: # if block_given? # map{|e| yield(e.send(meth, *args))} # else # map{|e| e.send(meth, *args)} # end # end #++ end facets-2.9.3/lib/core/facets/enumerable/occur.rb0000644000004100000410000000200011714455226021543 0ustar www-datawww-datamodule Enumerable # Returns an array of elements for the elements that occur n times. # Or according to the results of a given block. # # a = [1,1,2,3,3,4,5,5] # # a.occur(1).sort #=> [2,4] # a.occur(2).sort #=> [1,3,5] # a.occur(3).sort #=> [] # # a.occur(1..1).sort #=> [2,4] # a.occur(2..3).sort #=> [1,3,5] # # a.occur { |n| n == 1 }.sort #=> [2,4] # a.occur { |n| n > 1 }.sort #=> [1,3,5] # def occur(n=nil) #:yield: result = Hash.new { |hash, key| hash[key] = Array.new } self.each do |item| key = item result[key] << item end if block_given? result.reject! { |key, values| ! yield(values.size) } else raise ArgumentError unless n if Range === n result.reject! { |key, values| ! n.include?(values.size) } else result.reject! { |key, values| values.size != n } end end return result.values.flatten.uniq end end facets-2.9.3/lib/core/facets/enumerable/exclude.rb0000644000004100000410000000037611714455226022077 0ustar www-datawww-datamodule Enumerable unless method_defined?(:exclude?) # 1.9 # The inverse of #include?. # # [:a, :b].exclude?(:c) #=> true # [:a, :b].exclude?(:a) #=> false # def exclude?(object) !include?(object) end end end facets-2.9.3/lib/core/facets/enumerable/compact_map.rb0000644000004100000410000000122611714455226022724 0ustar www-datawww-datamodule Enumerable # A more versitle #compact method. It can be used to # collect and filter items out in one single step. # # c = [1,2,3].compact_map do |n| # n < 2 ? nil : n # end # # c #=> [2,3] # # CREDIT: Trans # # DEPRECATE: This method should probably be removed b/c #purge # does almost the same thing and enum.map{}.compact works too. def compact_map(&block) y = [] if block_given? each do |*a| r = yield(*a) y << r unless r.nil? end else each do |r| y << r unless r.nil? end end y end # alias_method :compact_collect, :compact_map end facets-2.9.3/lib/core/facets/enumerable/each_with_object.rb0000644000004100000410000000160111714455226023717 0ustar www-datawww-datamodule Enumerable unless method_defined?(:each_with_object) # A variation of #inject that saves one from having to # return the aggregate/memo argument. # # Say we want to count characters in a string. Using # the #each_with_object method we have: # # "string".each_with_object(Hash.new(0)) do |c, h| # h[c] += 1 # end # # versus using #inject which would be: # # "string".inject(Hash.new(0)) do |h, c| # h[c] +=1 # h # end # # Notice that the order of the block parameters is reversed. # # This method used be called #injecting and had the same # parameter order as #inject, but Ruby 1.9 has adopted this # method, so we support it instead. def each_with_object(memo) #:yield: each do |element| yield(element, memo) end memo end end end facets-2.9.3/lib/core/facets/to_hash.rb0000644000004100000410000001537711714455226017763 0ustar www-datawww-datarequire 'facets/enumerator' require 'facets/hash/dearray_values' class Array # Converts an array into a hash. Converting an array # into a hash is not a one-to-one conversion, for this # reason #to_h examines at the array being converted # and then dispatches the conversion to the most sutiable # specialized function. There are three possiblities for this. # # If the array is a collection of perfect pairs, like that # which Hash#to_a generates, then conversion is handled by # #to_h_flat. # # a = [ [:a,1], [:b,2] ] # a.to_h #=> { :a=>1, :b=>2 } # # If the array contains only arrays, but are not perfect pairs, # then #to_h_multi is called. # # a = [ [:a,1,2], [:b,2], [:c], [:d] ] # a.to_h #=> { :a=>[1,2], :b=>[2], :c=>[], :d=>[] } # # If the array contians objects other then arrays then # the #to_h_splat method is called. # # a = [ [:a,1,2], 2, :b, [:c,3], 9 ] # a.to_h #=> { [:a,1,2]=>2, :b=>[:c,3], 9=>nil } # # Finally, a particular dispatch can be forced by # specifying the +mode+ of conversion, eg. +:multi+, # +:splat+, +:flat+, +:assoc+, etc. # # Setting +mode+ to +true+ is the same as setting it +:multi+. # This has been left in for backward compatability. # # NOTE: The use of a +values+ parameter has been deprecated # because that functionality is as simple as ... # # array1.zip(array2).to_h # # CREDIT: Robert Klemme, Trans # #-- # The +True+ option in the case statement provides some # backward compatability with the previous versions of this # method. #++ def to_h(mode=nil) case mode when :splat return to_h_splat when :flat return to_h_flat when :multi, true return to_h_multi when :assoc return to_h_assoc else return to_h_auto end end # Converts an array into a hash. Converting an array # into a hash is not a one-to-one conversion, for this # reason #to_h examines at the array being converted # and then dispatches the conversion to the most sutiable # specialized function. There are three possiblities for this. # # If the array is a collection of perfect pairs, like that # which Hash#to_a generates, then conversion is handled by # #to_h_flat. # # a = [ [:a,1], [:b,2] ] # a.to_h_auto #=> { :a=>1, :b=>2 } # # If the array contains only arrays, but are not perfect pairs, # then #to_h_multi is called. # # a = [ [:a,1,2], [:b,2], [:c], [:d] ] # a.to_h_auto #=> { :a=>[1,2], :b=>[2], :c=>[], :d=>[] } # # If the array contians objects other then arrays then # the #to_h_splat method is called. # # a = [ [:a,1,2], 2, :b, [:c,3], 9 ] # a.to_h_auto #=> { [:a,1,2]=>2, :b=>[:c,3], 9=>nil } # def to_h_auto pairs = true mixed = false each do |e| case e when Array pairs = false if e.size > 2 else mixed = true end end if mixed to_h_splat elsif pairs to_h_flat else to_h_multi end end # This is equivalent to Hash[*array], but it will pad # the array with a +nil+ object if there are not an even number # of elements. # # a = [:a,1,:b,2,:c] # a.to_h_splat #=> { :a=>1, :b=>2, :c=>nil } # def to_h_splat a = dup a << nil if a.size % 2 == 1 Hash[*a] end # This is equivalent to Hash[*array.flatten], but it will pad # the array with a +nil+ object if there are not an even number # of elements. # # a = [:a,1,[:b,2,:c]] # a.to_h_flat #=> { :a=>1, :b=>2, :c=>nil } # def to_h_flat a = flatten a << nil if a.size % 2 == 1 Hash[*a] end #-- #def to_h_flat # each_slice(2).inject({}) {|ha,(k,v)| ha[k]=v; ha} #end #++ # When a mixed or multi-element accociative array # is used, the result is as follows: # # a = [ [:a,1,2], [:b,2], [:c], :d ] # a.to_h #=> { :a=>[1,2], :b=>[2], :c=>[], :d=>[] } # # If the first entry of any subelements are the same, then # the value will be set to the last occuring value. # # a = [ :x, [:x], [:x,1,2], [:x,3], [:x,4] ] # a.to_h_assoc #=> { :x=>[4] } # def to_h_assoc h = {} each do |k,*v| h[k] = v end h end # When a mixed or multi-element accociative array # is used, the result is as follows: # # a = [ [:a,1,2], [:b,2], [:c], :d ] # a.to_h #=> { :a=>[1,2], :b=>[2], :c=>[], :d=>[] } # # If the first entry of the subelements is the same, then # the values will be merged using #concat. # # a = [ [:a,1,2], [:a,3], [:a,4], [:a], :a ] # a.to_h_multi #=> { :a=>[1,2,3,4] } # def to_h_multi h = {} each do |k,*v| h[k] ||= [] h[k].concat(v) end h end #-- #def to_h_multi # inject({}) {|h,a| h[a.first] = a[1..-1]; h} #end # Is this a good idea? #def to_hash # h = {} # each_with_index do |v, i| # h[i] = v # end # h #end #++ end class Hash # Return a rehashing of _self_. # # {"a"=>1,"b"=>2}.to_h #=> {"b"=>2,"a"=>1} # # CREDIT: Forian Gross def to_h; rehash; end unless method_defined?(:to_hash) # 1.9.?+ # Returns _self_. def to_hash; self; end end end module Enumerable # Convert an Enumerable object into a hash by first # turning it into an array. # # CREDIT: Trans def to_h(mode=nil) to_a.to_h(mode) end def to_h_auto to_a.to_h_auto end def to_h_splat to_a.to_h_splat end def to_h_flat to_a.to_h_flat end def to_h_assoc to_a.to_h_assoc end def to_h_multi to_a.to_h_multi end #-- #def to_hash # to_a.to_hash #end #++ end class NilClass # Allows nil to create an empty hash, # similar to #to_a and #to_s. # # nil.to_h #=> {} # # CREDIT: Trans def to_h; {}; end end class Enumerator # Convert an Enumerator object into a hash. # This is equivalent to Array#to_h. # # e1 = [[1,:a],[2,:b],[3,:c]].to_enum # e1.to_h #=> { 1=>:a, 2=>:b, 3=>:c } # # e2 = [1,2,3,4,5].to_enum # e2.to_h #=> {5=>nil, 1=>2, 3=>4} # # e3 = [1,2,1,3,1,5].to_enum # e3.to_h #=> {1=>5} # # CREDIT: Sandor Szücs def to_h(mode=nil) to_a.to_h(mode) end # This is equivalent to Array#to_h_auto. # def to_h_auto to_a.to_h_auto end # This is equivalent to Array#to_h_splat. # def to_h_splat to_a.to_h_splat end # This is equivalent to Array#to_h_flat. # def to_h_flat to_a.to_h_flat end # This is equivalent to Array#to_h_assoc. # def to_h_assoc to_a.to_h_assoc end # This is equivalent to Array#to_h_multi. # def to_h_multi to_a.to_h_multi end end class Struct # Returns a hash containing the names and values # for all instance settings in the Struct. def to_h h = {} each_pair{ |k,v| h[k] = v } h end end facets-2.9.3/lib/core/facets/process/0000755000004100000410000000000011714455226017452 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/process/daemon.rb0000644000004100000410000000143311714455226021243 0ustar www-datawww-datamodule Process # Turns the current script into a daemon process # that detaches from the console. It can be shut # down with a TERM signal. # # CREDIT: David Heinemeier Hansson def self.daemon(nochdir=nil, noclose=nil) exit if fork # Parent exits, child continues. Process.setsid # Become session leader. exit if fork # Zap session leader. See [1]. unless nochdir Dir.chdir "/" # Release old working directory. end File.umask 0000 # Ensure sensible umask. Adjust as needed. unless noclose STDIN.reopen "/dev/null" # Free file descriptors and STDOUT.reopen "/dev/null", "a" # point them somewhere sensible. STDERR.reopen '/dev/null', 'a' end trap("TERM") { exit } return 0 end unless respond_to?(:daemon) end facets-2.9.3/lib/core/facets/float.rb0000644000004100000410000000011511714455226017423 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'float/round.rb' facets-2.9.3/lib/core/facets/unboundmethod/0000755000004100000410000000000011714455226020647 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/unboundmethod/arguments.rb0000644000004100000410000000153011714455226023200 0ustar www-datawww-dataclass UnboundMethod # Resolves the arguments of the method to have an # identical signiture --useful for preserving arity. # # class X # def foo(a, b); end # def bar(a, b=1); end # end # # foo_method = X.instance_method(:foo) # foo_method.arguments #=> "a0, a1" # # bar_method = X.instance_method(:bar) # bar_method.arguments #=> "a0, *args" # # When defaults are used the arguments must end in "*args". # # CREDIT: Trans def arguments ar = arity case ar <=> 0 when 1 args = [] ar.times do |i| args << "a#{i}" end args = args.join(", ") when 0 args = "" else ar = -ar - 1 args = [] ar.times do |i| args << "a#{i}" end args << "*args" args = args.join(", ") end return args end end facets-2.9.3/lib/core/facets/unboundmethod/name.rb0000644000004100000410000000077211714455226022122 0ustar www-datawww-dataclass UnboundMethod unless method_defined?(:name) # 1.8.7+ # Return the name of the method. # # Be aware that in ruby 1.9 UnboundMethod#name is defined already, # but it returns a Symbol not a String. # # class NameExample # def foo; end # end # # meth = NameExample.instance_method(:foo) # # meth.name.to_sym #=> :foo # # CREDIT: Trans def name i = to_s.rindex('#') to_s.slice(i+1...-1).to_sym end end end facets-2.9.3/lib/core/facets/matchdata/0000755000004100000410000000000011714455226017722 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/matchdata/matchset.rb0000644000004100000410000000215611714455226022063 0ustar www-datawww-dataclass MatchData # Returns [ pre_match, matchtree, post_match ]. (see matchtree) # # md = /(bb)(cc(dd))(ee)/.match "XXaabbccddeeffXX" # md.to_a #=> ["bbccddee", "bb", "ccdd", "dd", "ee"] # md.matchset #=> ["XXaa", [["bb"], ["cc", ["dd"]], ["ee"]], "ffXX"] # # CREDIT: Trans def matchset [pre_match, matchtree, post_match] end # An alternate to #to_a which returns the matches in # order corresponding with the regular expression. # # md = /(bb)(cc(dd))(ee)/.match "XXaabbccddeeffXX" # md.to_a #=> ["bbccddee", "bb", "ccdd", "dd", "ee"] # md.matchtree #=> [["bb"], ["cc", ["dd"]], ["ee"]] # # CREDIT: Trans def matchtree(index=0) ret=[] b, e=self.begin(index), self.end(index) while (index+=1)<=length if index==length || (bi=self.begin(index))>=e # we are finished, if something is left, then add it ret << string[b, e-b] if e>b break else if bi>=b ret << string[b, bi-b] if bi>b ret << matchtree(index) b=self.end(index) end end end return ret end end facets-2.9.3/lib/core/facets/matchdata/match.rb0000644000004100000410000000034411714455226021344 0ustar www-datawww-dataclass MatchData # Return the primary match string. This is equivalent to +md[0]+. # # md = /123/.match "123456" # md.match #=> "123" # # CREDIT: Martin DeMello def match(index=0) self[index] end end facets-2.9.3/lib/core/facets/file/0000755000004100000410000000000011714455226016713 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/file/sanitize.rb0000644000004100000410000000067411714455226021075 0ustar www-datawww-dataclass File # Cleans up a filename to ensure it will work on a filesystem. # # File.sanitize("yo+baby!") #=> 'yo+baby_' # File.sanitize(".what&up") #=> '.what_up' # # CREDIT: George Moschovitis def self.sanitize(filename) filename = File.basename(filename.gsub("\\", "/")) # work-around for IE filename.gsub!(/[^a-zA-Z0-9\.\-\+_]/,"_") filename = "_#{filename}" if filename =~ /^\.+$/ filename end end facets-2.9.3/lib/core/facets/file/atomic_id.rb0000644000004100000410000000013111714455226021163 0ustar www-datawww-dataclass File # def self.atomic_id @atomic_id ||= 0 @atomic_id += 1 end end facets-2.9.3/lib/core/facets/file/rewrite.rb0000644000004100000410000000502211714455226020720 0ustar www-datawww-dataclass File # Opens a file as a string and writes back the string to the file at # the end of the block. # # Returns the number of written bytes or +nil+ if the file wasn't # modified. # # Note that the file will even be written back in case the block # raises an exception. # # Mode can either be "b" or "+" and specifies to open the file in # binary mode (no mapping of the plattform's newlines to "\n" is # done) or to append to it. # # Assuming we had a file 'message.txt' and had a binary file 'binary.dat'. # # # Reverse contents of "message.txt" # File.rewrite("message.txt") { |str| str.reverse } # # # Replace "foo" by "bar" in "binary.dat". # File.rewrite("binary.dat", "b") { |str| str.gsub("foo", "bar") } # # IMPORTANT: The old version of this method required in place modification # of the file string. The new version will write whatever the block # returns instead!!! # # CREDIT: George Moschovitis # def self.rewrite(name, mode = "") #:yield: unless block_given? raise(ArgumentError, "Need to supply block to File.rewrite") end if mode.is_a?(Numeric) then flag, mode = mode, "" mode += "b" if flag & File::Constants::BINARY != 0 mode += "+" if flag & File::Constants::APPEND != 0 else mode.delete!("^b+") end old_str = open(name, "r#{mode}") { |file| file.read } #rescue "" old_str = old_str.clone begin new_str = yield(old_str) ensure if old_str != new_str open(name, "w#{mode}") { |file| file.write(new_str) } end end end # In place version of #rewrite. This version of method requires that the # string be modified in place within the block. # # # Reverse contents of "message" # File.rewrite("message.txt") { |str| str.reverse! } # # # Replace "foo" by "bar" in "binary" # File.rewrite("binary.dat", "b") { |str| str.gsub!("foo", "bar") } # def self.rewrite!(name, mode = "") #:yield: unless block_given? raise(ArgumentError, "Need to supply block to File.rewrite") end if mode.is_a?(Numeric) then flag, mode = mode, "" mode += "b" if flag & File::Constants::BINARY != 0 mode += "+" if flag & File::Constants::APPEND != 0 else mode.delete!("^b+") end old_str = open(name, "r#{mode}") { |file| file.read } #rescue "" new_str = old_str.clone begin yield(new_str) ensure if old_str != new_str open(name, "w#{mode}") { |file| file.write(new_str) } end end end end facets-2.9.3/lib/core/facets/file/rootname.rb0000644000004100000410000000101511714455226021061 0ustar www-datawww-dataclass File # Returns only the first portion of the directory of # a file path name. # # File.rootname('lib/jump.rb') #=> 'lib' # File.rootname('/jump.rb') #=> '/' # File.rootname('jump.rb') #=> '.' # # CREDIT: Trans # def self.rootname(path) # -- this should be fairly robust path_re = Regexp.new('[' + Regexp.escape(File::Separator + %q{\/}) + ']') head, tail = path.split(path_re, 2) return '.' if path == head return '/' if head.empty? return head end end facets-2.9.3/lib/core/facets/file/create.rb0000644000004100000410000000066711714455226020514 0ustar www-datawww-dataclass File # Creates a new file, or overwrites an existing file, # and writes a string into it. Can also take a block # just like File#open, which is yielded _after_ the # string is writ. # # str = 'The content for the file' # File.create('myfile.txt', str) # # CREDIT: George Moschovitis def self.create(path, str='', &blk) open(path, 'wb') do |f| f << str blk.call(f) if blk end end end facets-2.9.3/lib/core/facets/file/atomic_open.rb0000644000004100000410000000117111714455226021535 0ustar www-datawww-datarequire 'tempfile' unless defined?(Tempfile) require 'facets/file/atomic_id' class File # Same as `File.open`, but acts on a temporary copy of named # file, copying the file back to the original on completion. # # @uncommon # require 'facets/fileutils/atomic_open' # def self.atomic_open(file_name, mode="r", temp_dir=nil, &block) temp_dir = temp_dir || Dir.tmpdir temp_file = Tempfile.new("#{aomtic_id}-" + basename(file_name), temp_dir) if File.exist?(file_name) FileUtils.cp(file_name, temp_file) end open(temp_file, mode, &block) FileUtils.cp(temp_file, file_name) end end facets-2.9.3/lib/core/facets/file/ext.rb0000644000004100000410000000201611714455226020037 0ustar www-datawww-dataclass File # Takes a file name string and returns or changes its extension. # # Without a new extension argument, returns the extension of the # file name. In this respect #ext is like #extname, but unlike # #extname it does not include the dot prefix. # # With a new extension argument, changes the exension of the file # name to the new extension and returns it. # # Examples # # File.ext('file.rb') # => 'rb' # File.ext('file.rb', 'txt') # => 'file.txt' # File.ext('file.rb', '.txt') # => 'file.txt' # File.ext('file.rb', '') # => 'file' # # This method can be used with String#file for more object-oriented notation: # # 'file.rb'.file.ext('txt') # => 'file.txt' # # CREDIT: Lavir the Whiolet def self.ext(filename, new_ext=nil) old_ext = extname(filename) if new_ext == nil old_ext.sub(/^\./, '') else new_ext = '.' + new_ext unless (new_ext.empty? || new_ext[0,1] == '.') filename.chomp(old_ext) + new_ext end end end facets-2.9.3/lib/core/facets/file/null.rb0000644000004100000410000000040211714455226020206 0ustar www-datawww-dataclass File # Platform dependent null device. # # CREDIT: Daniel Burger def self.null case RUBY_PLATFORM when /mswin/i 'NUL' when /amiga/i 'NIL:' when /openvms/i 'NL:' else '/dev/null' end end end facets-2.9.3/lib/core/facets/file/split_all.rb0000644000004100000410000000073211714455226021225 0ustar www-datawww-dataclass File # Splits a file path into an array of individual path components. # This differs from File.split, which divides the path into # only two parts, directory path and basename. # # File.split_all("a/b/c") #=> ['a', 'b', 'c'] # # CREDIT: Trans def self.split_all(path) head, tail = File.split(path) return [tail] if head == '.' || tail == '/' return [head, tail] if head == '/' return split_all(head) + [tail] end end facets-2.9.3/lib/core/facets/file/write.rb0000644000004100000410000000076311714455226020400 0ustar www-datawww-dataclass File unless defined?(write) # 1.9+ # Writes the given data to the given path and closes the file. This is # done in binary mode, complementing IO.read in standard Ruby. # # str = 'The content for the file' # File.write('write.txt', str) # # Returns the number of bytes written. # # CREDIT: Gavin Sinclair def self.write(path, data) File.open(path, "wb") do |file| return file.write(data) end end end end facets-2.9.3/lib/core/facets/file/append.rb0000644000004100000410000000024411714455226020507 0ustar www-datawww-dataclass File # Append to a file. # # CREDIT: George Moschovitis def self.append(file, str) File.open(file, 'ab') { |f| f << str } end end facets-2.9.3/lib/core/facets/file/writelines.rb0000644000004100000410000000136511714455226021432 0ustar www-datawww-dataclass File # Writes the given array of data to the given path and closes the file. # This is done in binary mode, complementing IO.readlines in # standard Ruby. # # Note that +readlines+ (the standard Ruby method) returns an array of lines # with newlines intact, whereas +writelines+ uses +puts+, and so # appends newlines if necessary. In this small way, +readlines+ and # +writelines+ are not exact opposites. # # data = ['The content', ['for the file']] # File.writelines('writelines.txt', data) # # Returns number of lines written. # # CREDIT: Noah Gibbs, Gavin Sinclair def self.writelines(path, data) File.open(path, "wb") do |file| file.puts(data) end data.size end end facets-2.9.3/lib/core/facets/file/split_root.rb0000644000004100000410000000043111714455226021434 0ustar www-datawww-dataclass File # Return the head of path from the rest of the path. # # File.split_root('etc/xdg/gtk') #=> ['etc', 'xdg/gtk'] # def self.split_root(path) path_re = Regexp.new('[' + Regexp.escape(File::Separator + %q{\/}) + ']') path.split(path_re, 2) end end facets-2.9.3/lib/core/facets/file/read_binary.rb0000644000004100000410000000042311714455226021516 0ustar www-datawww-dataclass File # Read in a file as binary data. # # Assuming we had a binary file 'binary.dat'. # # File.read_binary('binary.dat') # # CREDIT: George Moschovitis def self.read_binary(fname) open(fname, 'rb') do |f| return f.read end end end facets-2.9.3/lib/core/facets/file/read_list.rb0000644000004100000410000000143711714455226021213 0ustar www-datawww-dataclass File # Reads in a file, removes blank lines and removes lines starting # with '#' and then returns an array of all the remaining lines. # # Thr remark indicator can be overridden via the +:omit:+ option, which # can be a regualar expression or a string that is match against the # start of a line. # # CREDIT: Trans def self.read_list(filepath, options={}) chomp = options[:chomp] omit = case options[:omit] when Regexp omit when nil /^\s*\#/ else /^\s*#{Regexp.escape(omit)}/ end list = [] readlines(filepath).each do |line| line = line.strip.chomp(chomp) next if line.empty? next if omit === line list << line end list end end facets-2.9.3/lib/core/facets/file/atomic_write.rb0000644000004100000410000000347111714455226021733 0ustar www-datawww-data# This is a precursor to the possibility of a more extensive Atomic File I/O # system. For now it simply provides a means for atomic file writing. require 'thread' unless defined?(Thread) require 'tempfile' unless defined?(Tempfile) require 'fileutils' unless defined?(FileUtils) class File # Write to a file atomically. Useful for situations where you don't # want other processes or threads to see half-written files. # # File.atomic_write("important.txt") do |file| # file.write("hello") # end # # If your temporary directory is not on the same filesystem as the file you're # trying to write, you can provide a different temporary directory. # # File.atomic_write("important.txt", "tmp") do |file| # file.write("hello") # end # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # CREDIT: David Heinemeier Hansson # # @uncommon # require 'facets/fileutils/atomic_write' # def self.atomic_write(file_name, temp_dir=nil) temp_dir = temp_dir || Dir.tmpdir temp_file = Tempfile.new(basename(file_name), temp_dir) yield temp_file temp_file.close begin ## Get original file permissions old_stat = stat(file_name) rescue Errno::ENOENT ## No old permissions, write a temp file to determine the defaults check_name = join(dirname(file_name), ".permissions_check.#{Thread.current.object_id}.#{Process.pid}.#{rand(1000000)}") open(check_name, "w") { } old_stat = stat(check_name) unlink(check_name) end ## Overwrite original file with temp file FileUtils.mv(temp_file.path, file_name) ## Set correct permissions on new file chown(old_stat.uid, old_stat.gid, file_name) chmod(old_stat.mode, file_name) end end facets-2.9.3/lib/core/facets/roman.rb0000644000004100000410000000374711714455226017450 0ustar www-datawww-dataclass Integer # ROMAN_MAX = 3999 unless const_defined?(:ROMAN_MAX) # ROMAN_VALUES = [ ["M", 1000], ["CM", 900], ["D", 500], ["CD", 400], ["C", 100], ["XC", 90], ["L", 50], ["XL", 40], ["X", 10], ["IX", 9], ["V", 5], ["IV", 4], ["I", 1] ] unless const_defined?(:ROMAN_VALUES) # Converts this integer to a roman numeral. # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # @uncommon # require 'facets/integer/roman' # def roman int = self #return nil if integer > ROMAN_MAX return "-#{(-int).roman}" if int < 0 return "" if int == 0 ROMAN_VALUES.each do |(i, v)| return(i + (int-v).roman) if v <= int end end end class String # Taken from O'Reilly's Perl Cookbook 6.23. Regular Expression Grabbag. ROMAN = /^M*(D?C{0,3}|C[DM])(L?X{0,3}|X[LC])(V?I{0,3}|I[VX])$/i unless const_defined?(:ROMAN) ROMAN_VALUES = Integer::ROMAN_VALUES.inject({}) do |h,(r,a)| h[r] = a; h end unless const_defined?(:ROMAN_VALUES) # Considers string a Roman numeral numeral, # and converts it to the corresponding integer. # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # @uncommon # require 'facets/string/roman' # def roman roman = upcase raise unless roman? last = roman[-1,1] roman.reverse.split('').inject(0) do |result, c| if ROMAN_VALUES[c] < ROMAN_VALUES[last] result -= ROMAN_VALUES[c] else last = c result += ROMAN_VALUES[c] end end end # Returns true iif the subject is a valid Roman numeral. # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # @uncommon # require 'facets/string/roman' # def roman? ROMAN =~ upcase end end facets-2.9.3/lib/core/facets/exception/0000755000004100000410000000000011714455226017772 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/exception/error_print.rb0000644000004100000410000000424111714455226022665 0ustar www-datawww-dataclass Exception # Formats the Exception so that it looks *familiar*, # i.e. exactly like your interpreter does it. # # Port of MRI native `error_print` function. # # @author Evgeniy Dolzhenko def self.error_print(e) warn_print = "" backtrace = e.backtrace backtrace = [ backtrace ] if backtrace.is_a?(String) # 1.9 returns single String for SystemStackError warn_print << backtrace[0] if e.is_a?(RuntimeError) && e.message.empty? warn_print << ": unhandled exception\n" else if e.message.empty? warn_print << ": #{ e.class.name }\n" else split_message = e.message.split("\n") warn_print << ": " if split_message.size == 1 warn_print << "#{ e.message } (#{ e.class.name })\n" else warn_print << split_message[0] warn_print << " (#{ e.class.name })\n" warn_print << split_message[1..-1].join("\n").chomp << "\n" end end end len = backtrace.size ## int skip = eclass == rb_eSysStackError; skip = e.is_a?(SystemStackError) ## #define TRACE_MAX (TRACE_HEAD+TRACE_TAIL+5) ## #define TRACE_HEAD 8 ## #define TRACE_TAIL 5 trace_head = 8 trace_tail = 5 trace_max = (trace_head + trace_tail + 5) ## ## for (i = 1; i < len; i++) { i = 1 while i < len ## if (TYPE(ptr[i]) == T_STRING) { ## warn_printf("\tfrom %s\n", RSTRING_PTR(ptr[i])); ## } warn_print << "\tfrom %s\n" % e.backtrace[i] ## if (skip && i == TRACE_HEAD && len > TRACE_MAX) { if skip && i == trace_head && len > trace_max ## warn_printf("\t ... %ld levels...\n", ## len - TRACE_HEAD - TRACE_TAIL); warn_print << "\t ... %d levels...\n" % (len - trace_head - trace_tail) ## i = len - TRACE_TAIL; i = len - trace_tail ## } end ## } i += 1 end warn_print end # Formats the Exception so that it looks *familiar*, # i.e. exactly like your interpreter does it. # # @author Evgeniy Dolzhenko # # @todo Anyone have a better name for this method? def error_print Exception.error_print(self) end end facets-2.9.3/lib/core/facets/exception/detail.rb0000644000004100000410000000056111714455226021563 0ustar www-datawww-dataclass Exception # Pretty string output of exception/error object useful for helpful # debug messages. # # @author George Moschovitis def detail if backtrace %{#{self.class.name}: #{message}\n #{backtrace.join("\n ")}\n LOGGED FROM: #{caller[0]}} else %{#{self.class.name}: #{message}\n LOGGED FROM: #{caller[0]}} end end end facets-2.9.3/lib/core/facets/exception/suppress.rb0000644000004100000410000000077411714455226022213 0ustar www-datawww-dataclass Exception # Supress errors while executing a block, with execptions. # # CREDIT: David Heinemeier Hansson, Thomas Sawyer def self.suppress(*exception_classes) exception_classes.each do |e| unless e < self raise ArgumentError, "exception #{e} not a subclass of #{self}" end end exception_classes = [self] | exception_classes begin yield rescue Exception => e raise unless exception_classes.any? { |cls| e.kind_of?(cls) } end end end facets-2.9.3/lib/core/facets/exception/raised.rb0000644000004100000410000000026011714455226021564 0ustar www-datawww-dataclass Exception # Does a block raise an a given +exception+. # def self.raised? #:yeild: begin yield false rescue self true end end end facets-2.9.3/lib/core/facets/kernel.rb0000644000004100000410000000601611714455226017604 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'kernel/as.rb' require_relative 'kernel/ask.rb' require_relative 'kernel/assign.rb' require_relative 'kernel/assign_from.rb' require_relative 'kernel/attr_singleton.rb' require_relative 'kernel/blank.rb' require_relative 'kernel/callstack.rb' require_relative 'kernel/call_stack.rb' require_relative 'kernel/case.rb' require_relative 'kernel/complete.rb' require_relative 'kernel/constant.rb' require_relative 'kernel/d.rb' require_relative 'kernel/deep_clone.rb' require_relative 'kernel/deep_copy.rb' #require_relative 'kernel/demo.rb' # uncommon require_relative 'kernel/disable_warnings.rb' require_relative 'kernel/eigen.rb' #require_relative 'kernel/eigenclass.rb' # uncommon require_relative 'kernel/enable_warnings.rb' require_relative 'kernel/equate.rb' require_relative 'kernel/ergo.rb' require_relative 'kernel/extend.rb' require_relative 'kernel/extension.rb' require_relative 'kernel/false.rb' require_relative 'kernel/here.rb' #require_relative 'kernel/hierarchical_send' # uncommon require_relative 'kernel/identical.rb' require_relative 'kernel/in.rb' require_relative 'kernel/instance_assign.rb' require_relative 'kernel/instance_class.rb' #require_relative 'kernel/instance_exec.rb' # uncommon require_relative 'kernel/instance_send.rb' require_relative 'kernel/load_all.rb' require_relative 'kernel/load_relative.rb' require_relative 'kernel/maybe.rb' #require_relative 'kernel/memo.rb' # uncommon require_relative 'kernel/meta_alias.rb' require_relative 'kernel/meta_class.rb' require_relative 'kernel/meta_def.rb' require_relative 'kernel/meta_eval.rb' require_relative 'kernel/method.rb' require_relative 'kernel/no.rb' require_relative 'kernel/not.rb' require_relative 'kernel/not_nil.rb' require_relative 'kernel/object_class.rb' require_relative 'kernel/object_hexid.rb' require_relative 'kernel/object_send.rb' require_relative 'kernel/p.rb' require_relative 'kernel/presence.rb' require_relative 'kernel/present.rb' require_relative 'kernel/qua_class.rb' require_relative 'kernel/require_all.rb' require_relative 'kernel/require_relative.rb' require_relative 'kernel/respond.rb' require_relative 'kernel/returning.rb' require_relative 'kernel/silence.rb' require_relative 'kernel/silence_warnings.rb' require_relative 'kernel/singleton_class.rb' require_relative 'kernel/source_location.rb' require_relative 'kernel/super_method.rb' require_relative 'kernel/tap.rb' require_relative 'kernel/temporarily.rb' #require_relative 'kernel/trap_chain.rb' # uncommon require_relative 'kernel/true.rb' require_relative 'kernel/try.rb' require_relative 'kernel/val.rb' require_relative 'kernel/with.rb' require_relative 'kernel/writers.rb' #require_relative 'kernel/y.rb' # uncommon require_relative 'kernel/yes.rb' require_relative 'kernel/__callee__.rb' require_relative 'kernel/__class__.rb' require_relative 'kernel/__dir__.rb' require_relative 'kernel/__get__.rb' require_relative 'kernel/__method__.rb' require_relative 'kernel/__set__.rb' facets-2.9.3/lib/core/facets/numeric/0000755000004100000410000000000011714455226017436 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/numeric/round.rb0000644000004100000410000000227011714455226021113 0ustar www-datawww-dataclass Numeric # Conceptually, rounding is expected to apply to floating point numbers. # However it can actually be applied to pretty much any Numeric object. # For example, one could round an Integer to the nearest kilo. # # See Float#round_at. def round_at(*args) to_f.round_at(*args) end # See Float#round_to. def round_to(*args) to_f.round_to(*args) end end =begin class Integer # See Float#round_at. def round_at(*args) to_f.round_at(*args) end # See Float#round_to. def round_to(*args) to_f.round_to(*args) end end =end class Float # Rounds to the given decimal position. # # 4.555.round_at(0) #=> 5.0 # 4.555.round_at(1) #=> 4.6 # 4.555.round_at(2) #=> 4.56 # 4.555.round_at(3) #=> 4.555 # # CREDIT: Trans def round_at( d ) #d=0 (self * (10.0 ** d)).round.to_f / (10.0 ** d) end # Rounds to the nearest _n_th degree. # # 4.555.round_to(1) #=> 5.0 # 4.555.round_to(0.1) #=> 4.6 # 4.555.round_to(0.01) #=> 4.56 # 4.555.round_to(0) #=> 4.555 # # CREDIT: Trans def round_to( n ) #n=1 return self if n == 0 (self * (1.0 / n)).round.to_f / (1.0 / n) end end facets-2.9.3/lib/core/facets/numeric/spacing.rb0000644000004100000410000000046511714455226021414 0ustar www-datawww-dataclass Numeric # Returns the size of the string representation of # a numerical value. # # 1.spacing #=> 1 # 10.spacing #=> 2 # 100.spacing #=> 3 # -100.spacing #=> 4 # 1.2.spacing #=> 3 # # CREDIT: Victor H. Goff III def spacing to_s.length end end facets-2.9.3/lib/core/facets/numeric/close.rb0000644000004100000410000000004011714455226021062 0ustar www-datawww-datarequire 'facets/numeric/approx' facets-2.9.3/lib/core/facets/numeric/distance.rb0000644000004100000410000000040611714455226021555 0ustar www-datawww-dataclass Numeric # Returns the distance between self an another value. # This is the same as #- but it provides an alternative # for common naming between variant classes. # # 4.distance(3) #=> 1 # def distance(other) self - other end end facets-2.9.3/lib/core/facets/numeric/positive.rb0000644000004100000410000000024611714455226021627 0ustar www-datawww-dataclass Numeric # Is a number greater than zero. # def positive? self > 0 end # Is a number less than zero. # def negative? self < 0 end end facets-2.9.3/lib/core/facets/numeric/approx.rb0000644000004100000410000000206111714455226021273 0ustar www-datawww-dataclass Numeric # Determines if another number is approximately equal within a given # _n_th degree. Defaults to 100ths if the degree is not specified. # # Currently defaults to 1/10,000,000 if the degree is not specified. # But this may change once a "most commonly useful" factor is determined. # # This is the same a {#close?} but has a different defualt. # # @author Gavin Sinclair def approx?(x, n=0.0000001) close?(x, n) end # Determines if another number is approximately equal # within a given +epsilon+. # # This is the same a {#approx?} but has a different defualt. # # @author Gavin Sinclair def close?(number, epsilon=0.01) return(self == number) if epsilon.zero? a, b = self.to_f, number.to_f if a.zero? or b.zero? ## There's no scale, so we can only go on difference. (a - b).abs < @epsilon else ## We go by ratio. The ratio of two equal numbers is one, so the ratio ## of two practically-equal floats will be very nearly one. (a/b - 1).abs < epsilon end end end facets-2.9.3/lib/core/facets/numeric/negative.rb0000644000004100000410000000004211714455226021561 0ustar www-datawww-datarequire 'facets/numeric/positive' facets-2.9.3/lib/core/facets/numeric/round_to.rb0000644000004100000410000000003711714455226021614 0ustar www-datawww-datarequire 'facets/numeric/round' facets-2.9.3/lib/core/facets/numeric/length.rb0000644000004100000410000000014711714455226021246 0ustar www-datawww-dataclass Numeric # Returns +self+, useful for polymorphic cases. # def length self end end facets-2.9.3/lib/core/facets/numeric/round_at.rb0000644000004100000410000000003711714455226021576 0ustar www-datawww-datarequire 'facets/numeric/round' facets-2.9.3/lib/core/facets/enumerator/0000755000004100000410000000000011714455226020155 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/enumerator/fx.rb0000644000004100000410000000113611714455226021120 0ustar www-datawww-data# for Ruby 1.8 -> 1.9 transition unless defined?(::Enumerator) begin require 'enumerator' Enumerator = Enumerable::Enumerator unless defined? ::Enumerator rescue LoadError # Ruby 1.9 already has it built-in. end end require 'facets/functor' class Enumerator # def fx Functor.new(&method(:fx_send).to_proc) end private # def fx_send(op, *a, &b) map{ |e| e.send(op, *a, &b) } end ## TODO: When no longer needed to support 1.8.6 we can use: ## ## # ## def fx ## Functor.new do |op, *a, &b| ## map{ |e| e.send(op, *a, &b) } ## end ## end end facets-2.9.3/lib/core/facets/regexp.rb0000644000004100000410000000033711714455226017616 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'regexp/arity.rb' require_relative 'regexp/multiline.rb' require_relative 'regexp/op_add.rb' require_relative 'regexp/op_or.rb' require_relative 'regexp/to_re.rb' facets-2.9.3/lib/core/facets/process.rb0000644000004100000410000000012011714455226017770 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'process/daemon.rb' facets-2.9.3/lib/core/facets/integer/0000755000004100000410000000000011714455226017431 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/integer/odd.rb0000644000004100000410000000121411714455226020522 0ustar www-datawww-dataclass Integer unless method_defined?(:odd?) # 1.8.7+ # Returns true if this integer is odd, false otherwise. # # 2.odd? #=> false # 3.odd? #=> true # # -99.odd? # -> true # -98.odd? # -> false # # CREDIT: Daniel Schierbeck def odd? self & 1 == 1 #self % 2 == 1 end end unless method_defined?(:even?) # 1.8.7+ # Returns true if this integer is even, false otherwise. # # 2.even? #=> true # 3.even? #=> false # # CREDIT: Daniel Schierbeck def even? self & 1 == 0 #self % 2 == 0 end end end facets-2.9.3/lib/core/facets/integer/bitmask.rb0000644000004100000410000000267311714455226021420 0ustar www-datawww-dataclass Integer # Set a bit. # # 0.bit(4) #=> 16 # # Using a negative figure will clear a bit. # # 10.bit(-4) #=> 2 # # This is more easily seen using binary. # # 0b0100.bit(-3) #=> 0 # # CREDIT: Thomas Sawyer, George Moschovitis def bit(bit) if bit < 0 mask = (1 << ~bit) self & ~mask else mask = (1 << bit) self | mask end end # Clear bit. # # CREDIT: George Moschovitis def bit_clear(bit) mask = (1 << bit) self & ~mask end # Is a bit set? # # 8.bit?(3) #=> true # 8.bit?(2) #=> false # # CREDIT: Thomas Sawyer, George Moschovitis def bit?(bit) mask = (1 << bit) (self & mask) != 0 end # Apply a bitmask. # # 1.bitmask(6) #=> 7 # # Using a inverted bitmask clears bits. # # 7.bitmask(~2) #=> 5 # 5.bitmask(~2) #=> 5 # # CREDIT: George Moschovitis def bitmask(mask) if mask < 0 self & mask else self | mask end end # Is bitmask set? # # 7.bitmask?(7) #=> true # 7.bitmask?(5) #=> true # 8.bitmask?(3) #=> false # # CREDIT: George Moschovitis def bitmask?(mask) (self & mask) != 0 end end module Kernel # Create a single bit bitmask. # # Bit(0) #=> 1 # Bit(1) #=> 2 # Bit(2) #=> 4 # # This is equivalent to n-shift: "1 << n". # # CREDIT: Thomas Sawyer, George Moschovitis def Bit(n) 1 << Integer(n) end end facets-2.9.3/lib/core/facets/integer/roman.rb0000644000004100000410000000002711714455226021071 0ustar www-datawww-datarequire 'facets/roman' facets-2.9.3/lib/core/facets/integer/of.rb0000644000004100000410000000046011714455226020362 0ustar www-datawww-dataclass Integer # Like #times but returns a collection of the yield results. # # a = 3.of { |i| "#{i+1}" } # a #=> [ "1", "2", "3" ] # def of(&block) Array.new(self, &block) end # Time warn aliases for #of. alias_method :times_collect, :of alias_method :times_map, :of end facets-2.9.3/lib/core/facets/integer/even.rb0000644000004100000410000000003511714455226020711 0ustar www-datawww-datarequire 'facets/integer/odd' facets-2.9.3/lib/core/facets/integer/factorial.rb0000644000004100000410000000045611714455226021727 0ustar www-datawww-dataclass Integer # Calculate the factorial of an integer. # # 2.factorial #=> 2 # 3.factorial #=> 6 # 4.factorial #=> 24 # # CREDIT: Malte Milatz def factorial return 1 if zero? f = 1 2.upto(self) { |n| f *= n } f end alias_method( :fac, :factorial ) end facets-2.9.3/lib/core/facets/integer/bit.rb0000644000004100000410000000004111714455226020527 0ustar www-datawww-datarequire 'facets/integer/bitmask' facets-2.9.3/lib/core/facets/integer/multiple.rb0000644000004100000410000000042211714455226021607 0ustar www-datawww-dataclass Integer # Is +self+ a multiple of a given number? # # 7.multiple?(2) #=> false # 8.multiple?(2) #=> true # # CREDIT: Trans def multiple?(number) if number.zero? zero? ? true : false else self % number == 0 end end end facets-2.9.3/lib/core/facets/integer/ordinal.rb0000644000004100000410000000051411714455226021406 0ustar www-datawww-dataclass Integer def ordinal if [11,12,13].include?(self % 100) "#{self}th" else case (self % 10) when 1 "#{self}st" when 2 "#{self}nd" when 3 "#{self}rd" else "#{self}th" end end end # Rails term. alias_method :ordinalize, :ordinal end facets-2.9.3/lib/core/facets/range.rb0000644000004100000410000000042011714455226017411 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'range/combine.rb' require_relative 'range/overlap.rb' #require_relative 'range/quantile.rb' # uncommon require_relative 'range/to_r.rb' require_relative 'range/umbrella.rb' require_relative 'range/within.rb' facets-2.9.3/lib/core/facets/fixnum.rb0000644000004100000410000000015011714455226017623 0ustar www-datawww-dataclass Fixnum n_bits = ([42].pack('L!').size * 8) MAX = 2 ** (n_bits - 2) - 1 MIN = -MAX - 1 end facets-2.9.3/lib/core/facets/module.rb0000644000004100000410000000556411714455226017620 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'module/abstract.rb' require_relative 'module/alias_accessor.rb' require_relative 'module/alias_method_chain.rb' require_relative 'module/alias_module_function.rb' require_relative 'module/all_instance_methods.rb' require_relative 'module/ancestor.rb' require_relative 'module/anonymous.rb' #require_relative 'module/attr_class_accessor.rb' # uncommon require_relative 'module/attr_setter.rb' #require_relative 'module/attr_tester.rb' # uncommon #require_relative 'module/attr_validator.rb' # uncommon require_relative 'module/basename.rb' require_relative 'module/can.rb' #require_relative 'module/cattr.rb' # uncommon require_relative 'module/class.rb' #require_relative 'module/class_accessor.rb' # uncommon require_relative 'module/class_def.rb' #require_relative 'module/class_extend.rb' # uncommon #require_relative 'module/class_inheritor.rb' # uncommon require_relative 'module/class_method_defined.rb' #require_relative 'module/copy_inheritor.rb' # uncommon #require_relative 'module/enclosure.rb' # uncommon #require_relative 'module/enclosures.rb' # uncommon require_relative 'module/extend.rb' require_relative 'module/home.rb' require_relative 'module/homename.rb' require_relative 'module/housing.rb' #require_relative 'module/include_as.rb' # uncommon #require_relative 'module/instance_function.rb' # uncommon require_relative 'module/include_function_module.rb' require_relative 'module/instance_method.rb' require_relative 'module/instance_method_defined.rb' require_relative 'module/integrate.rb' require_relative 'module/is.rb' #require_relative 'module/let.rb' # uncommon #require_relative 'module/memoize.rb' # uncommon #require_relative 'module/method_clash.rb' # uncommon #require_relative 'module/method_space.rb' # uncommon require_relative 'module/methodize.rb' require_relative 'module/modname.rb' require_relative 'module/module_def.rb' #require_relative 'module/module_load.rb' # uncommon require_relative 'module/nodef.rb' require_relative 'module/op.rb' require_relative 'module/op_add.rb' require_relative 'module/op_mul.rb' require_relative 'module/op_sub.rb' require_relative 'module/pathize.rb' #require_relative 'module/preextend.rb' # uncommon require_relative 'module/redefine_method.rb' require_relative 'module/redirect_method.rb' require_relative 'module/remove.rb' require_relative 'module/rename_method.rb' require_relative 'module/revise.rb' require_relative 'module/set.rb' require_relative 'module/singleton_method_defined.rb' require_relative 'module/spacename.rb' require_relative 'module/to_obj.rb' require_relative 'module/wrap_method.rb' facets-2.9.3/lib/core/facets/enumerable.rb0000644000004100000410000000277311714455226020451 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'enumerable/accumulate.rb' require_relative 'enumerable/cluster_by.rb' require_relative 'enumerable/collect_with_index.rb' require_relative 'enumerable/compact_map.rb' require_relative 'enumerable/count.rb' require_relative 'enumerable/defer.rb' require_relative 'enumerable/each_by.rb' require_relative 'enumerable/each_with_object.rb' require_relative 'enumerable/every.rb' require_relative 'enumerable/ewise.rb' require_relative 'enumerable/exclude.rb' require_relative 'enumerable/expand.rb' require_relative 'enumerable/filter.rb' require_relative 'enumerable/find_yield.rb' require_relative 'enumerable/frequency.rb' require_relative 'enumerable/graph.rb' require_relative 'enumerable/group_by.rb' require_relative 'enumerable/incase.rb' require_relative 'enumerable/map_by.rb' require_relative 'enumerable/map_detect.rb' require_relative 'enumerable/map_send.rb' require_relative 'enumerable/map_with.rb' require_relative 'enumerable/map_with_index.rb' require_relative 'enumerable/mash.rb' require_relative 'enumerable/modulate.rb' require_relative 'enumerable/none.rb' require_relative 'enumerable/occur.rb' require_relative 'enumerable/one.rb' require_relative 'enumerable/per.rb' require_relative 'enumerable/purge.rb' require_relative 'enumerable/recursively.rb' require_relative 'enumerable/sum.rb' require_relative 'enumerable/take.rb' require_relative 'enumerable/uniq_by.rb' require_relative 'enumerable/visit.rb' require_relative 'enumerable/zip_map.rb' facets-2.9.3/lib/core/facets/lazy.rb0000644000004100000410000001433511714455226017306 0ustar www-datawww-data# = Lazy # # Everything you need for Lazy evaluation in Ruby. # # == Authors # # * MenTaLguY # # == Copying # # Copyright (c) 2005 MenTaLguY # # Ruby License # # This module is free software. You may use, modify, and/or redistribute this # software under the same terms as Ruby. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. # Everything you need for Lazy evaluation in Ruby. # # @author MenTaLguY module Lazy # Raised when a demanded computation diverges (e.g. if it tries to directly # use its own result) class DivergenceError < Exception #:nodoc: def initialize( message="Computation diverges" ) super( message ) end end # Wraps an exception raised by a lazy computation. # # The reason we wrap such exceptions in LazyException is that they need to # be distinguishable from similar exceptions which might normally be raised # by whatever strict code we happen to be in at the time. class LazyException < DivergenceError #:nodoc: # the original exception attr_reader :reason def initialize( reason ) @reason = reason super( "Exception in lazy computation: #{ reason } (#{ reason.class })" ) set_backtrace( reason.backtrace.dup ) if reason end end # = Promise # # A handle for a promised computation. They are transparent, so that in # most cases, a promise can be used as a proxy for the computation's result # object. The one exception is truth testing -- a promise will always look # true to Ruby, even if the actual result object is nil or false. # # If you want to test the result for truth, get the unwrapped result object # via Kernel.demand. class Promise alias __class__ class #:nodoc: instance_methods.each { |m| undef_method m unless m =~ /^(__|object_|instance_)/ } def initialize( &computation ) #:nodoc: @computation = computation end def __synchronize__ #:nodoc: yield end # Create this once here, rather than creating a proc object for every evaluation. DIVERGES = lambda { raise DivergenceError.new } # Differentiate inspection of DIVERGES lambda. def DIVERGES.inspect "DIVERGES" end def __result__ #:nodoc: __synchronize__ do if @computation raise LazyException.new( @exception ) if @exception computation = @computation @computation = DIVERGES # trap divergence due to over-eager recursion begin @result = demand( computation.call( self ) ) @computation = nil rescue DivergenceError raise rescue Exception => exception # handle exceptions @exception = exception raise LazyException.new( @exception ) end end @result end end def inspect #:nodoc: __synchronize__ do if @computation "#<#{ __class__ } computation=#{ @computation.inspect }>" else @result.inspect end end end def respond_to?( message ) #:nodoc: message = message.to_sym message == :__result__ or message == :inspect or __result__.respond_to? message end def method_missing( *args, &block ) #:nodoc: __result__.__send__( *args, &block ) end end # = PromiseSafe # # Thread safe version of Promise class. class PromiseSafe < Promise def __synchronize__ #:nodoc: current = Thread.current Thread.critical = true unless @computation # fast path for evaluated thunks Thread.critical = false yield else if @owner == current Thread.critical = false raise DivergenceError.new end while @owner # spinlock Thread.critical = false Thread.pass Thread.critical = true end @owner = current Thread.critical = false begin yield ensure @owner = nil end end end end # = Future # # Future class subclasses PromiseSafe. class Future < PromiseSafe def initialize( &computation ) #:nodoc: result = nil exception = nil thread = Thread.new do begin result = computation.call( self ) rescue Exception => exception end end super() do raise DivergenceError.new if Thread.current == thread thread.join raise exception if exception result end end end end module Kernel # The promise() function is used together with demand() to implement # lazy evaluation. It returns a promise to evaluate the provided # block at a future time. Evaluation can be demanded and the block's # result obtained via the demand() function. # # Implicit evaluation is also supported: the first message sent to it will # demand evaluation, after which that message and any subsequent messages # will be forwarded to the result object. # # As an aid to circular programming, the block will be passed a promise # for its own result when it is evaluated. Be careful not to force # that promise during the computation, lest the computation diverge. # def promise( &computation ) #:yields: result Lazy::Promise.new(&computation) end # Forces the result of a promise to be computed (if necessary) and returns # the bare result object. Once evaluated, the result of the promise will # be cached. Nested promises will be evaluated together, until the first # non-promise result. # # If called on a value that is not a promise, it will simply return it. # def demand( promise ) if promise.respond_to? :__result__ promise.__result__ else # not really a promise promise end end # Schedules a computation to be run asynchronously in a background thread # and returns a promise for its result. An attempt to demand the result of # the promise will block until the computation finishes. # # As with Kernel.promise, this passes the block a promise for its own result. # Use wisely. # def future( &computation ) #:yields: result Lazy::Future.new(&computation) end end facets-2.9.3/lib/core/facets/objectspace/0000755000004100000410000000000011714455226020256 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/objectspace/reflect.rb0000644000004100000410000000321611714455226022231 0ustar www-datawww-datarequire 'facets/functor' module ObjectSpace # Reflection ensures that information about an object # is actual according to Ruby's Kernel definitions, just # in case such methods have been overridden. # # ObjectSpace.reflect("object").object_id # # There is also a global short-cut for this method to ease # meta-programming with it. # # $ref["object"].class # # Typically theis method will be used to gather the object's # id, as in the example given, or it's class, but any Kernel # method can be used. # # Care should be taken in utilizing this technique. In most # cases it is not needed, but in certain cases is useful # for improving the robustness of meta-programming solutions. # # Note that this is also equivalent to using +as(Kernel)+ ... # # "object".as(Kernel).object_id # # But obviously, in this case there is the risk that #as has # be overridden too. # def self.reflect(obj) ## TODO: use this after 1.8.6 support discontinued ## Functor.new do |op, *a, &b| ## Kernel.instance_method(op).bind(obj).call(*a, &b) ## end Reflector.new(obj) end # class Reflector #:nodoc: instance_methods(true).each{ |m| private m unless /^(__|object_id$)/ =~ m.to_s } def initialize(obj) @obj = obj end def method_missing(op, *args, &yld) Kernel.instance_method(op).bind(@obj).call(*args, &yld) end end end # Shorcut for +ObjectSpace.reflect+. $ref = lambda do |obj| ## TODO: use this after 1.8.6 support discontinued ## Functor.new do |meth, *a, &b| ## Kernel.instance_method(meth).bind(obj).call(*a, &b) ## end ObjectSpace.reflect(obj) end facets-2.9.3/lib/core/facets/objectspace/op_fetch.rb0000644000004100000410000000006611714455226022374 0ustar www-datawww-dataclass << ObjectSpace alias_method :[], :_id2ref end facets-2.9.3/lib/core/facets/objectspace/classes.rb0000644000004100000410000000027511714455226022244 0ustar www-datawww-datamodule ObjectSpace # @return All the classes in the object space. def self.classes klasses = [] each_object(Class){|o| klasses << o} klasses end end facets-2.9.3/lib/core/facets/binding/0000755000004100000410000000000011714455226017406 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/binding/call_stack.rb0000644000004100000410000000004311714455226022030 0ustar www-datawww-datarequire 'facets/kernel/call_stack' facets-2.9.3/lib/core/facets/binding/op_get.rb0000644000004100000410000000065111714455226021212 0ustar www-datawww-datarequire 'facets/binding/eval' class Binding # Returns the value of some variable. # # a = 2 # binding["a"] #=> 2 # def []( x ) eval( x.to_s ) end # Set the value of a local variable. # # binding["a"] = 4 # a #=> 4 # # @deprecated No longer wortks in Ruby 1.9+. # # @see Binding#with for an alternative. def []=( l, v ) eval( "lambda {|v| #{l} = v}").call( v ) end end facets-2.9.3/lib/core/facets/binding/__callee__.rb0000644000004100000410000000004011714455226021746 0ustar www-datawww-datarequire 'facets/binding/caller' facets-2.9.3/lib/core/facets/binding/op_set.rb0000644000004100000410000000004011714455226021216 0ustar www-datawww-datarequire 'facets/binding/op_get' facets-2.9.3/lib/core/facets/binding/__method__.rb0000644000004100000410000000004011714455226022001 0ustar www-datawww-datarequire 'facets/binding/caller' facets-2.9.3/lib/core/facets/binding/caller.rb0000644000004100000410000000146411714455226021202 0ustar www-datawww-datarequire 'facets/binding/eval' require 'facets/binding/call_stack' require 'facets/kernel/__method__' class Binding # Returns the call stack, same format as Kernel#caller() # def caller( skip=0 ) eval("caller(#{skip})") end # Return the line number on which the binding was created. # def __LINE__ Kernel.eval("__LINE__", self) end # Returns file name in which the binding was created. # def __FILE__ Kernel.eval("__FILE__", self) end # Return the directory of the file in which the binding was created. # def __DIR__ File.dirname(self.__FILE__) end # Retreive the current running method. # def __method__ Kernel.eval("__method__", self) end # Retreive the current running method. # def __callee__ Kernel.eval("__callee__", self) end end facets-2.9.3/lib/core/facets/binding/local_variables.rb0000644000004100000410000000045311714455226023057 0ustar www-datawww-datarequire 'facets/binding/eval' class Binding # Returns the local variables defined in the binding context: # # a = 1 # b = 2 # # binding.local_variables #=> [:a, :b] # # TODO: Rename this to prevent name clash? def local_variables() eval("local_variables") end end facets-2.9.3/lib/core/facets/binding/eval.rb0000644000004100000410000000031211714455226020656 0ustar www-datawww-dataclass Binding unless method_defined?(:eval) # 1.8.7+ # Evaluate a Ruby source code string (or block) in the binding context. def eval(str) Kernel.eval(str, self) end end end facets-2.9.3/lib/core/facets/binding/with.rb0000644000004100000410000000040111714455226020701 0ustar www-datawww-dataclass Binding # Returns a new binding with local varaibles set. # # CREDIT: Trans def with(_local_variables, &_yields) eval("lambda{ |#{_local_variables.keys.join(',')},&yields| binding }").call(*_local_variables.values, &_yields) end end facets-2.9.3/lib/core/facets/binding/defined.rb0000644000004100000410000000033311714455226021330 0ustar www-datawww-datarequire 'facets/binding/eval' class Binding # Returns the nature of something within the context of the binding. # Returns nil if that thing is not defined. def defined?(x) eval("defined? #{x}") end end facets-2.9.3/lib/core/facets/binding/self.rb0000644000004100000410000000042111714455226020661 0ustar www-datawww-datarequire 'facets/binding/eval' class Binding # already defined by Rubinius # Kernel.eval('Rubinius::VariableScope.current.self', self) unless method_defined?(:self) # Returns self of the binding's context. def self eval('self') end end end facets-2.9.3/lib/core/facets/binding/op.rb0000644000004100000410000000017111714455226020350 0ustar www-datawww-data# This file is here for backward compatibility only. # It can be deprecated eventually. require 'facets/binding/op_get' facets-2.9.3/lib/core/facets/binding/callstack.rb0000644000004100000410000000004411714455226021672 0ustar www-datawww-datarequire 'facets/binding/call_stack' facets-2.9.3/lib/core/facets/hash.rb0000644000004100000410000000362011714455226017245 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'hash/alias.rb' require_relative 'hash/argumentize.rb' require_relative 'hash/at.rb' require_relative 'hash/autonew.rb' require_relative 'hash/collate.rb' require_relative 'hash/count.rb' require_relative 'hash/data.rb' require_relative 'hash/dearray_values.rb' require_relative 'hash/deep_merge.rb' require_relative 'hash/delete.rb' require_relative 'hash/delete_at.rb' require_relative 'hash/delete_unless.rb' require_relative 'hash/delete_values.rb' require_relative 'hash/diff.rb' require_relative 'hash/except.rb' require_relative 'hash/graph.rb' require_relative 'hash/insert.rb' require_relative 'hash/inverse.rb' require_relative 'hash/join.rb' require_relative 'hash/keys.rb' require_relative 'hash/mash.rb' require_relative 'hash/new_with.rb' require_relative 'hash/op.rb' require_relative 'hash/op_add.rb' require_relative 'hash/op_and.rb' require_relative 'hash/op_mul.rb' require_relative 'hash/op_or.rb' require_relative 'hash/op_push.rb' require_relative 'hash/op_sub.rb' require_relative 'hash/recurse.rb' require_relative 'hash/recursively.rb' require_relative 'hash/rekey.rb' require_relative 'hash/replace_each.rb' require_relative 'hash/reverse_merge.rb' require_relative 'hash/select.rb' require_relative 'hash/slice.rb' require_relative 'hash/stringify_keys.rb' require_relative 'hash/subset.rb' require_relative 'hash/swap.rb' require_relative 'hash/symbolize_keys.rb' require_relative 'hash/to_h.rb' require_relative 'hash/to_mod.rb' require_relative 'hash/to_options.rb' require_relative 'hash/to_proc.rb' require_relative 'hash/to_struct.rb' require_relative 'hash/traverse.rb' require_relative 'hash/update.rb' require_relative 'hash/update_each.rb' require_relative 'hash/update_keys.rb' require_relative 'hash/update_values.rb' #require_relative 'hash/url_params.rb' # uncommon require_relative 'hash/weave.rb' require_relative 'hash/zip.rb' facets-2.9.3/lib/core/facets/struct/0000755000004100000410000000000011714455226017320 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/struct/attributes.rb0000644000004100000410000000037411714455226022037 0ustar www-datawww-dataclass Struct # Returns a hash containing the names and values # for all instance settings in the Struct. # # This will eventually be deprecated in favor of #to_h. def attributes h = {} each_pair { |k,v| h[k] = v } h end end facets-2.9.3/lib/core/facets/enumerator.rb0000644000004100000410000000325111714455226020503 0ustar www-datawww-dataif RUBY_VERSION < '1.9' require 'enumerator' # for Ruby 1.8 -> 1.9 transition Enumerator = Enumerable::Enumerator unless defined?(::Enumerator) class Enumerator private alias :old_initialize :initialize # Provides the ruby-1.9 block form of Enumerator, where you can write: # # obj = Enumerator.new do |yielder| # # ... # yielder.yield(data) # or: yielder << data # # ... # end # # When obj.each is called, the block is run once. It should call # yielder.yield with each item it wishes to generate. # # Example: # # fib = Enumerator.new { |y| # a = b = 1 # loop { # y << a # a, b = b, a + b # } # } # # fib.take(10) #=> [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] # def initialize(*args, &block) if block @body = block old_initialize(self, :_start) else old_initialize(*args) end end def _start(*args,&receiver) #:nodoc: @body.call(Yielder.new(&receiver), *args) end # Wrapper to allow yielder.yield(output) or yielder << output # in the same way as ruby-1.9 # # TODO: Why can't Yielder take a block instead of a proc argument? class Yielder #:nodoc: def initialize(&proc) @proc = proc end def yield(*args) @proc[*args] end alias :<< :yield end end end path = __FILE__.chomp('.rb') base = File.basename(path) Dir[File.join(path, '*.rb')].each do |lib| #require lib # why is this so much slower? require "facets/#{base}/#{File.basename(lib)}" end facets-2.9.3/lib/core/facets/array.rb0000644000004100000410000000410111714455226017433 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'array/after.rb' require_relative 'array/before.rb' require_relative 'array/collapse.rb' require_relative 'array/collisions.rb' require_relative 'array/combination.rb' require_relative 'array/commonality.rb' require_relative 'array/conjoin.rb' require_relative 'array/contains.rb' require_relative 'array/delete.rb' require_relative 'array/delete_unless.rb' require_relative 'array/delete_values.rb' require_relative 'array/divide.rb' require_relative 'array/duplicates.rb' require_relative 'array/each_pair.rb' require_relative 'array/each_value.rb' require_relative 'array/entropy.rb' require_relative 'array/extract_options.rb' require_relative 'array/from.rb' require_relative 'array/index.rb' require_relative 'array/indexable.rb' #require_relative 'array/median.rb' # uncommon require_relative 'array/merge.rb' require_relative 'array/mode.rb' require_relative 'array/nonuniq.rb' require_relative 'array/not_empty.rb' require_relative 'array/only.rb' require_relative 'array/pad.rb' require_relative 'array/peek.rb' #require_relative 'array/percentile.rb' # uncommon require_relative 'array/permutation.rb' require_relative 'array/poke.rb' require_relative 'array/probability.rb' require_relative 'array/product.rb' require_relative 'array/pull.rb' require_relative 'array/occurent.rb' #require_relative 'array/op_pow.rb' # uncommon require_relative 'array/recurse.rb' require_relative 'array/recursively.rb' require_relative 'array/rotate.rb' require_relative 'array/select.rb' require_relative 'array/splice.rb' require_relative 'array/split.rb' require_relative 'array/store.rb' require_relative 'array/thru.rb' require_relative 'array/traverse.rb' require_relative 'array/uniq_by.rb' #folder = __FILE__.chomp('.rb') #target = File.basename(folder) #loader = \ # if RUBY_VERSION < '1.9' # lambda{ |file| require File.join(folder, file) } # else # lambda{ |file| require_relative File.join(target, file) } # end #files.each do |file| # next unless file.end_with?('.rb') # loader.call(file) #end facets-2.9.3/lib/core/facets/file.rb0000644000004100000410000000105611714455226017242 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'file/append.rb' #require_relative 'file/atomic_write.rb' # uncommon require_relative 'file/create.rb' require_relative 'file/ext.rb' require_relative 'file/null.rb' require_relative 'file/read_binary.rb' require_relative 'file/read_list.rb' require_relative 'file/rewrite.rb' require_relative 'file/rootname.rb' require_relative 'file/sanitize.rb' require_relative 'file/split_all.rb' require_relative 'file/split_root.rb' require_relative 'file/write.rb' require_relative 'file/writelines.rb' facets-2.9.3/lib/core/facets/struct.rb0000644000004100000410000000012311714455226017641 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'struct/attributes.rb' facets-2.9.3/lib/core/facets/time.rb0000644000004100000410000000104211714455226017254 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'time/ago.rb' require_relative 'time/change.rb' require_relative 'time/dst_adjustment.rb' require_relative 'time/elapse.rb' require_relative 'time/future.rb' require_relative 'time/hence.rb' require_relative 'time/in.rb' require_relative 'time/less.rb' require_relative 'time/past.rb' require_relative 'time/round_to.rb' require_relative 'time/set.rb' require_relative 'time/shift.rb' require_relative 'time/stamp.rb' require_relative 'time/to_time.rb' require_relative 'time/trunc.rb' facets-2.9.3/lib/core/facets/class/0000755000004100000410000000000011714455226017101 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/class/preallocate.rb0000644000004100000410000000270111714455226021721 0ustar www-datawww-dataclass Class # Designate aspect modules to be added to a object at instantiation. # # class Firetruck # def put_out_fire(option) # "Put out #{option}" # end # end # # module FastFiretruck # def put_out_fire(option) # super("very #{option}!") # end # end # # Firetruck.preallocate(FastFiretruck) # # ft = Firetruck.new # ft.put_out_fire('fast') #=> "Put out very fast!" # # This method is very similar to the idea of #prepend, but it has some # limitations in that it works by overriding #new and #allocate and extends # an object with the aspect modules on instantiation. A true #prepend # implementation would not have to do this --but would be a natural part # of the class heirarchy instead. For this reason, this method has been # named #preallocate, rather than #prepend. # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # CREDIT: Trans # # @uncommon # require 'facets/class/preallocate' # def preallocate(aspect) _new = method(:new) _allocate = method(:allocate) (class << self; self; end).class_eval do define_method(:new) do |*args| o = _new.call(*args) o.extend aspect o end define_method(:allocate) do |*args| o = _allocate.call(*args) o.extend aspect o end end end end facets-2.9.3/lib/core/facets/class/descendants.rb0000644000004100000410000000137411714455226021726 0ustar www-datawww-datarequire 'facets/class/subclasses' class Class # List all descedents of this class. # # class A ; end # class B < A; end # class C < A; end # A.descendants #=> [B,C] # # You may also limit the generational distance the subclass may be from # the parent class. # # class X ; end # class Y < X; end # class Z < Y; end # X.descendants #=> [Y,Z] # X.descendants(1) #=> [Y] # # NOTE: This is a intensive operation. Do not expect it to be very fast. # # @author Roger Pack def descendants(generations=-1) descendants = [] subclasses.each do |k| descendants << k if generations != 1 descendants.concat(k.descendants(generations - 1)) end end descendants end end facets-2.9.3/lib/core/facets/class/pathize.rb0000644000004100000410000000043611714455226021075 0ustar www-datawww-datarequire 'facets/string/pathize' class Class # Converts a class name to a unix path. # # module ::Example # class PathizeExample # end # end # # Example::PathizeExample.pathize #=> "example/pathize_example" # def pathize name.pathize end end facets-2.9.3/lib/core/facets/class/subclasses.rb0000644000004100000410000000102111714455226021567 0ustar www-datawww-dataclass Class if defined?(Class.__subclasses__) # Rubinius # Returns an array with the direct children of +self+. # # Integer.subclasses # => [Fixnum, Bignum] # alias_method :subclasses, :__subclasses__ else # Returns an array with the direct children of +self+. # # Integer.subclasses # => [Fixnum, Bignum] # def subclasses list = [] ObjectSpace.each_object(Class) do |c| list.unshift c if c.superclass == self end list.uniq end end end facets-2.9.3/lib/core/facets/class/methodize.rb0000644000004100000410000000047111714455226021420 0ustar www-datawww-datarequire 'facets/string/methodize' class Class # Translate a class name to a suitable method name. # # module ::Example # class MethodizeExample # end # end # # Example::MethodizeExample.methodize #=> "example__methodize_example" # def methodize name.methodize end end facets-2.9.3/lib/core/facets/class/to_proc.rb0000644000004100000410000000066711714455226021104 0ustar www-datawww-dataclass Class # Convert instatiation of a class into a Proc. # # class Person # def initialize(name) # @name = name # end # # def inspect # @name.to_str # end # end # # persons = %w(john bob jane hans).map(&Person) # # persons.map{ |p| p.inspect } #=> ['john', 'bob', 'jane', 'hans'] # # CREDIT: Daniel Schierbeck def to_proc proc{|*args| new(*args)} end end facets-2.9.3/lib/core/facets/class/hierarchically.rb0000644000004100000410000000040711714455226022412 0ustar www-datawww-datamodule Kernel # Hierarchically apply a block, passing each ancestor to the block # starting at the root ancestor and working toward the current object. # def hierarchically(&block) ancestors.reverse_each do |m| block.call(m) end end end facets-2.9.3/lib/core/facets/class/singleton.rb0000644000004100000410000000033411714455226021430 0ustar www-datawww-dataclass Class # Return true if a class is the singleton class of # an object. # # @uncommon # require 'facets/class/singleton' # def singleton? ! ancestors.include?( self ) rescue false end end facets-2.9.3/lib/core/facets/string/0000755000004100000410000000000011714455226017302 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/string/line_wrap.rb0000644000004100000410000000047611714455226021616 0ustar www-datawww-dataclass String # Line wrap at width. # # s = "1234567890".line_wrap(5) # # s #=> "12345\n67890\n" # # CREDIT: Trans def line_wrap(width, tabs=4) s = gsub(/\t/,' ' * tabs) # tabs default to 4 spaces s = s.gsub(/\n/,' ') r = s.scan( /.{1,#{width}}/ ) r.join("\n") << "\n" end end facets-2.9.3/lib/core/facets/string/mscan.rb0000644000004100000410000000041311714455226020726 0ustar www-datawww-dataclass String # Like #scan but returns MatchData ($~) rather # then matched string ($&). # # CREDIT: Trans def mscan(re) #:yield: if block_given? scan(re) { yield($~) } else m = [] scan(re) { m << $~ } m end end end facets-2.9.3/lib/core/facets/string/divide.rb0000644000004100000410000000056511714455226021101 0ustar www-datawww-dataclass String # Breaks a string up into an array based on a regular expression. # Similar to scan, but includes the matches. # # s = "

Thisisa test.

" # s.divide( /\<.*?\>/ ) # #=> ["

This", "is", "a test.", "

"] # # CREDIT: Trans def divide( re ) re2 = /#{re}.*?(?=#{re}|\Z)/ scan(re2) #{re}(?=#{re})/) end end facets-2.9.3/lib/core/facets/string/capitalized.rb0000644000004100000410000000172311714455226022123 0ustar www-datawww-dataclass String # Return true if the string is capitalized, otherwise false. # # "This".capitalized? #=> true # "THIS".capitalized? #=> false # "this".capitalized? #=> false # # Note Ruby's strange concept of capitalized. See capitalcase # for the more command conception. # # CREDIT: Phil Tomson def capitalized? capitalize == self end # Return true if the string is lowercase (downcase), otherwise false. # # "THIS".downcase? #=> false # "This".downcase? #=> false # "this".downcase? #=> true # # CREDIT: Phil Tomson def downcase? downcase == self end # Alias for #downcase? method. # alias_method :lowercase?, :downcase? # Is the string upcase/uppercase? # # "THIS".upcase? #=> true # "This".upcase? #=> false # "this".upcase? #=> false # # CREDIT: Phil Tomson def upcase? upcase == self end # Alias for #upcase? method. # alias_method :uppercase?, :upcase? end facets-2.9.3/lib/core/facets/string/modulize.rb0000644000004100000410000000143511714455226021462 0ustar www-datawww-dataclass String # Converts a string to module name representation. # # This is essentially #camelcase, but it also converts # '/' to '::' which is useful for converting paths to # namespaces. # # Examples # # "method_name".modulize #=> "MethodName" # "method/name".modulize #=> "Method::Name" # def modulize #gsub('__','/'). # why was this ever here? gsub(/__(.?)/){ "::#{$1.upcase}" }. gsub(/\/(.?)/){ "::#{$1.upcase}" }. gsub(/(?:_+|-+)([a-z])/){ $1.upcase }. gsub(/(\A|\s)([a-z])/){ $1 + $2.upcase } end # Compare to ActiveSupport's definition: # # gsub(/__(.?)/){ "::#{$1.upcase}" }. # gsub(/\/(.?)/){ "::#{$1.upcase}" }. # gsub(/(?:_+)([a-z])/){ $1.upcase }. # gsub(/(^|\s+)([a-z])/){ $1 + $2.upcase } # end facets-2.9.3/lib/core/facets/string/margin.rb0000644000004100000410000000121711714455226021105 0ustar www-datawww-dataclass String # Provides a margin controlled string. # # x = %Q{ # | This # | is # | margin controlled! # }.margin # # NOTE: This may still need a bit of tweaking. # # TODO: describe its limits and caveats and edge cases # # CREDIT: Trans def margin(n=0) #d = /\A.*\n\s*(.)/.match( self )[1] #d = /\A\s*(.)/.match( self)[1] unless d d = ((/\A.*\n\s*(.)/.match(self)) || (/\A\s*(.)/.match(self)))[1] return '' unless d if n == 0 gsub(/\n\s*\Z/,'').gsub(/^\s*[#{d}]/, '') else gsub(/\n\s*\Z/,'').gsub(/^\s*[#{d}]/, ' ' * n) end end end facets-2.9.3/lib/core/facets/string/bracket.rb0000644000004100000410000000271711714455226021251 0ustar www-datawww-dataclass String BRA2KET = { '['=>']', '('=>')', '{'=>'}', '<'=>'>' } # Return a new string embraced by given brackets. # If only one bracket char is given it will be placed # on either side. # # "wrap me".bracket('{') #=> "{wrap me}" # "wrap me".bracket('--','!') #=> "--wrap me!" # # CREDIT: Trans def bracket(bra, ket=nil) #ket = String.bra2ket[$&] if ! ket && /^[\[({<]$/ =~ bra ket = BRA2KET[bra] unless ket "#{bra}#{self}#{ket ? ket : bra}" end # Inplace version of #bracket. # # CREDIT: Trans def bracket!(bra, ket=nil) self.replace(bracket(bra, ket)) end # Return a new string with the given brackets removed. # If only one bracket char is given it will be removed # from either side. # # "{unwrap me}".unbracket('{') #=> "unwrap me" # "--unwrap me!".unbracket('--','!') #=> "unwrap me" # # CREDIT: Trans def unbracket(bra=nil, ket=nil) if bra ket = BRA2KET[bra] unless ket ket = ket ? ket : bra s = self.dup s.gsub!(%r[^#{Regexp.escape(bra)}], '') s.gsub!(%r[#{Regexp.escape(ket)}$], '') return s else if m = BRA2KET[ self[0,1] ] return self.slice(1...-1) if self[-1,1] == m end end return self.dup # if nothing else end # Inplace version of #unbracket. # # CREDIT: Trans def unbracket!(bra=nil, ket=nil) self.replace( unbracket(bra, ket) ) end # TODO: rename #bracket to #embrace ? end facets-2.9.3/lib/core/facets/string/lchomp.rb0000644000004100000410000000073311714455226021114 0ustar www-datawww-dataclass String # Left chomp. # # "help".lchomp("h") #=> "elp" # "help".lchomp("k") #=> "help" # # CREDIT: Trans def lchomp(match) if index(match) == 0 self[match.size..-1] else self.dup end end # In-place left chomp. # # "help".lchomp("h") #=> "elp" # "help".lchomp("k") #=> "help" # # CREDIT: Trans def lchomp!(match) if index(match) == 0 self[0...match.size] = '' self end end end facets-2.9.3/lib/core/facets/string/uppercase.rb0000644000004100000410000000077711714455226021631 0ustar www-datawww-dataclass String # Upcase first letter. # # NOTE: One might argue that this method should behave the same as # +#upcase+ and rather this behavior should be in place of +#captialize+. # Probably so, but since Matz has already defined +#captialize+ the way # it is, this name seems most fitting to the missing behavior. # def uppercase str = to_s str[0,1].upcase + str[1..-1] end # Downcase first letter. # def lowercase str = to_s str[0,1].downcase + str[1..-1] end end facets-2.9.3/lib/core/facets/string/words.rb0000644000004100000410000000022111714455226020760 0ustar www-datawww-dataclass String # Returns an array of characters. # # "abc 123".words #=> ["abc","123"] # def words self.split(/\s+/) end end facets-2.9.3/lib/core/facets/string/nchar.rb0000644000004100000410000000136511714455226020727 0ustar www-datawww-dataclass String # Returns _n_ characters of the string. If _n_ is positive # the characters are from the beginning of the string. # If _n_ is negative from the end of the string. # # str = "this is text" # # str.nchar(4) #=> "this" # str.nchar(-4) #=> "text" # # Alternatively a replacement string can be given, which will # replace the _n_ characters. # # str.nchar(4, 'that') #=> "that is text" # # The original string remains unaffected. # # str #=> "this is text" # def nchar(n, replacement=nil) if replacement s = self.dup n > 0 ? (s[0...n] = replacement) : (s[n..-1] = replacement) s else n > 0 ? self[0...n] : self[n..-1] end end end facets-2.9.3/lib/core/facets/string/op_sub.rb0000644000004100000410000000031411714455226021114 0ustar www-datawww-dataclass String # Removes occurances of a string or regexp. # # ("HELLO HELLO" - "LL") #=> "HEO HEO" # # CREDIT: Benjamin David Oakes def -(pattern) self.gsub(pattern, '') end end facets-2.9.3/lib/core/facets/string/interpolate.rb0000644000004100000410000000060511714455226022156 0ustar www-datawww-dataclass String # Interpolate. Provides a means of extenally using Ruby string # interpolation mechinism. # # try = "hello" # str = "\#{try}!!!" # String.interpolate{ str } #=> "hello!!!" # # NOTE: The block neccessary in order to get then binding of the caller. # # CREDIT: Trans def self.interpolate(&str) eval "%{#{str.call}}", str.binding end end facets-2.9.3/lib/core/facets/string/lines.rb0000644000004100000410000000053011714455226020737 0ustar www-datawww-dataclass String unless method_defined?(:lines) # 1.8.7+ # Returns an array of characters. # # "abc\n123".lines.to_a #=> ["abc\n","123"] # def lines(&blk) if block_given? each_line(&blk) #scan(/$.*?\n/).each(&blk) else Enumerator.new(self, :lines) #.split(/\n/) end end end end facets-2.9.3/lib/core/facets/string/unquote.rb0000644000004100000410000000003611714455226021326 0ustar www-datawww-datarequire 'facets/string/quote' facets-2.9.3/lib/core/facets/string/range_all.rb0000644000004100000410000000003611714455226021552 0ustar www-datawww-datarequire 'facets/string/range' facets-2.9.3/lib/core/facets/string/rewrite.rb0000644000004100000410000000104011714455226021303 0ustar www-datawww-dataclass String # Apply a set of rules in the form of regular expression matches # to the string. # # * rules - The array containing rule-pairs (match, write). # # Keep in mind that the order of rules is significant. # # Returns the rewritten String. # # CREDIT: George Moschovitis def rewrite(rules) raise ArgumentError.new('The rules parameter is nil') unless rules rewritten_string = dup rules.each do |(match,write)| rewritten_string.gsub!(match,write) end return rewritten_string end end facets-2.9.3/lib/core/facets/string/outdent.rb0000644000004100000410000000003711714455226021311 0ustar www-datawww-datarequire 'facets/string/indent' facets-2.9.3/lib/core/facets/string/briefcase.rb0000644000004100000410000000004211714455226021546 0ustar www-datawww-datarequire 'facets/string/titlecase' facets-2.9.3/lib/core/facets/string/tab.rb0000644000004100000410000000037611714455226020403 0ustar www-datawww-datarequire 'facets/string/tabto' class String # Aligns each line n spaces. # # CREDIT: Gavin Sinclair # def tab(n) gsub(/^ */, ' ' * n) end # NOTE: Deprecated #taballto which was an alias for #tab. #alias_method :taballto, :tab end facets-2.9.3/lib/core/facets/string/each_char.rb0000644000004100000410000000133711714455226021530 0ustar www-datawww-dataclass String unless method_defined?(:each_char) # 1.9 require 'strscan' # Yields a single-character string for each character in the string. # When $KCODE = 'UTF8', multi-byte characters are yielded appropriately. # # a = '' # "HELLO".each_char{ |c| a << "#{c.downcase}" } # a #=> 'hello' # def each_char # :yield: scanner, char = StringScanner.new(self), /./mu loop{ yield(scanner.scan(char) || break) } end #-- # Iterates through each character. This is a little faster than # using #chars b/c it does not create the intermediate array... # # def each_char # :yield: # size.times{ |i| yield(self[i,1]) } # end #++ end end facets-2.9.3/lib/core/facets/string/compress_lines.rb0000644000004100000410000000053611714455226022660 0ustar www-datawww-dataclass String # Matches any whitespace (including newline) and replaces with a single space # # string = <<-QUERY.compress_lines # SELECT name # FROM users # QUERY # # string #=> "SELECT name FROM users" # def compress_lines(spaced = true) split($/).map{ |line| line.strip }.join(spaced ? ' ' : '') end end facets-2.9.3/lib/core/facets/string/unfold.rb0000644000004100000410000000076411714455226021125 0ustar www-datawww-dataclass String # Unfold paragrpahs. # # FIXME: Sometimes adds one too many blank lines. TEST!!! # def unfold blank = false text = '' split(/\n/).each do |line| if /\S/ !~ line text << "\n\n" blank = true else if /^(\s+|[*])/ =~ line text << (line.rstrip + "\n") else text << (line.rstrip + " ") end blank = false end end text = text.gsub(/(\n){3,}/,"\n\n") text.rstrip end end facets-2.9.3/lib/core/facets/string/cleanlines.rb0000644000004100000410000000101411714455226021740 0ustar www-datawww-datarequire "facets/enumerator" class String # Returns an Enumerator for iterating over each # line of the string, stripped of whitespace on # either side. # # "this\nthat\nother\n".cleanlines.to_a #=> ['this', 'that', 'other'] # def cleanlines(&block) if block scan(/^.*?$/) do |line| block.call(line.strip) end else str = self Enumerator.new do |output| str.scan(/^.*?$/) do |line| output.yield(line.strip) end end end end end facets-2.9.3/lib/core/facets/string/start_with.rb0000644000004100000410000000273011714455226022021 0ustar www-datawww-data#-- # = Developer's Notes # # Old definition of start_with? written by Lucas Carlson # and Blaine Cook was ... # # index(prefix) == 0 # # I like the simplicity of this definition, but I could not # find a way define #end_with? in similar terms and still # accept regular expressions for the suffix. So I had to use # Regexp match. On th upside, we can get MatchData # which might be more useful. #++ class String #unless method_defined?(:start_with?) # 1.8.7+ # Does a string start with the given prefix? # # "hello".start_with?("he") #=> true # "hello".start_with?("to") #=> false # # Note: This definition is better than standard Ruby's # becuase it handles regular expressions. # # CREDIT: Juris Galang def start_with?(prefix) prefix = Regexp.escape(prefix.to_s) unless Regexp===prefix /^#{prefix}/.match(self) ? true : false end #end #unless method_defined?(:end_with?) # 1.8.7+ # Does a string end with the given suffix? # # "hello".end_with?("lo") #=> true # "hello".end_with?("to") #=> false # # Note: This definition is better than standard Ruby's # becuase it handles regular expressions. # # CREDIT: Juris Galang def end_with?(suffix) suffix = Regexp.escape(suffix.to_s) unless Regexp===suffix /#{suffix}$/.match(self) ? true : false end #end alias_method :starts_with?, :start_with? alias_method :ends_with? , :end_with? end facets-2.9.3/lib/core/facets/string/pathize.rb0000644000004100000410000000143111714455226021272 0ustar www-datawww-dataclass String # Transforms a namespace, i.e. a class or module name, into a viable # file path. # # "ExamplePathize".pathize #=> "example_pathize" # "ExamplePathize::Example".pathize #=> "example_pathize/example" # # Compare this method to {String#modulize) and {String#methodize). # def pathize gsub(/([A-Z]+)([A-Z])/,'\1_\2'). gsub(/([a-z])([A-Z])/,'\1_\2'). gsub('__','/'). gsub('::','/'). gsub(/\s+/, ''). # spaces are bad form gsub(/[?%*:|"<>.]+/, ''). # reserved characters downcase end # Compare to Rails definition: # # gsub(/__/, '/'). # gsub(/::/, '/'). # gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). # gsub(/([a-z\d])([A-Z])/,'\1_\2'). # tr("-", "_"). # downcase # end facets-2.9.3/lib/core/facets/string/roman.rb0000644000004100000410000000002711714455226020742 0ustar www-datawww-datarequire 'facets/roman' facets-2.9.3/lib/core/facets/string/cmp.rb0000644000004100000410000000004011714455226020400 0ustar www-datawww-datarequire 'facets/comparable/cmp' facets-2.9.3/lib/core/facets/string/store.rb0000644000004100000410000000010311714455226020755 0ustar www-datawww-dataclass String # Alias for []=. alias_method :store, :[]= end facets-2.9.3/lib/core/facets/string/variablize.rb0000644000004100000410000000034411714455226021760 0ustar www-datawww-dataclass String # Prepend an "@" to the beginning of a string # to make a instance variable name. This also replaces # non-valid characters with underscores. def variablize v = gsub(/\W/, '_') "@#{v}" end end facets-2.9.3/lib/core/facets/string/unbracket.rb0000644000004100000410000000004011714455226021577 0ustar www-datawww-datarequire 'facets/string/bracket' facets-2.9.3/lib/core/facets/string/camelcase.rb0000644000004100000410000000402211714455226021542 0ustar www-datawww-dataclass String # Converts a string to camelcase. This method leaves the first character # as given. This allows other methods to be used first, such as #uppercase # and #lowercase. # # "camel_case".camelcase #=> "camelCase" # "Camel_case".camelcase #=> "CamelCase" # # Custom +separators+ can be used to specify the patterns used to determine # where capitalization should occur. By default these are underscores (`_`) # and space characters (`\s`). # # "camel/case".camelcase('/') #=> "camelCase" # # If the first separator is a symbol, either `:lower` or `:upper`, then # the first characters of the string will be downcased or upcased respectively. # # "camel_case".camelcase(:upper) #=> "CamelCase" # # Note that this implementation is different from ActiveSupport's. # If that is what you are looking for you may want {#modulize}. # def camelcase(*separators) case separators.first when Symbol, TrueClass, FalseClass, NilClass first_letter = separators.shift end separators = ['_', '\s'] if separators.empty? str = self.dup separators.each do |s| str = str.gsub(/(?:#{s}+)([a-z])/){ $1.upcase } end case first_letter when :upper, true str = str.gsub(/(\A|\s)([a-z])/){ $1 + $2.upcase } when :lower, false str = str.gsub(/(\A|\s)([A-Z])/){ $1 + $2.downcase } end str end # Same as +#camelcase+ but converts first letter to uppercase. # # "camel_case".upper_camelcase #=> "CamelCase" # "Camel_case".upper_camelcase #=> "CamelCase" # # @deprecated # Use `#camelcase(:upper)` instead. # def upper_camelcase(*separators) camelcase(:upper, *separators) end # Same as +#camelcase+ but converts first letter to lowercase. # # "camel_case".lower_camelcase #=> "camelCase" # "Camel_case".lower_camelcase #=> "camelCase" # # @deprecated # Use `#camelcase(:lower)` instead. # def lower_camelcase(*separators) camelcase(:lower, *separators) end end facets-2.9.3/lib/core/facets/string/fold.rb0000644000004100000410000000141111714455226020550 0ustar www-datawww-dataclass String # Returns a new string with all new lines removed from # adjacent lines of text. # # s = "This is\na test.\n\nIt clumps\nlines of text." # s.fold # # _produces_ # # "This is a test.\n\nIt clumps lines of text. " # # One arguable flaw with this, that might need a fix: # if the given string ends in a newline, it is replaced with # a single space. # # CREDIT: Trans def fold(ignore_indented=false) ns = '' i = 0 br = self.scan(/(\n\s*\n|\Z)/m) do |m| b = $~.begin(1) e = $~.end(1) nl = $& tx = slice(i...b) if ignore_indented and slice(i...b) =~ /^[ ]+/ ns << tx else ns << tx.gsub(/[ ]*\n+/,' ') end ns << nl i = e end ns end end facets-2.9.3/lib/core/facets/string/natcmp.rb0000644000004100000410000000525211714455226021115 0ustar www-datawww-data#-- # Adapted from: # # * http://sourcefrog.net/projects/natsort/natcmp.rb # # Based on Martin Pool's "Natural Order String Comparison" originally # written in C. (see http://sourcefrog.net/projects/natsort/) # # This implementation is Copyright (C) 2003 by Alan Davies # # # This software is provided 'as-is', without any express or implied # warranty. In no event will the authors be held liable for any damages # arising from the use of this software. # # Permission is granted to anyone to use this software for any purpose, # including commercial applications, and to alter it and redistribute it # freely, subject to the following restrictions: # # 1. The origin of this software must not be misrepresented; you must not # claim that you wrote the original software. If you use this software # in a product, an acknowledgment in the product documentation would be # appreciated but is not required. # 2. Altered source versions must be plainly marked as such, and must not be # misrepresented as being the original software. # 3. This notice may not be removed or altered from any source distribution. #++ # class String # 'Natural order' comparison of strings, e.g. ... # # "my_prog_v1.1.0" < "my_prog_v1.2.0" < "my_prog_v1.10.0" # # which does not follow alphabetically. A secondary # parameter, if set to _true_, makes the comparison # case insensitive. # # "Hello.1".natcmp("Hello.10") #=> -1 # # TODO: Invert case flag? # # @author Alan Davies # @author Martin Pool def natcmp(str2, caseInsensitive=false) str1 = self.dup str2 = str2.dup compareExpression = /^(\D*)(\d*)(.*)$/ if caseInsensitive str1.downcase! str2.downcase! end # -- remove all whitespace str1.gsub!(/\s*/, '') str2.gsub!(/\s*/, '') while (str1.length > 0) or (str2.length > 0) do # -- extract non-digits, digits and rest of string str1 =~ compareExpression chars1, num1, str1 = $1.dup, $2.dup, $3.dup str2 =~ compareExpression chars2, num2, str2 = $1.dup, $2.dup, $3.dup # -- compare the non-digits case (chars1 <=> chars2) when 0 # Non-digits are the same, compare the digits... # If either number begins with a zero, then compare alphabetically, # otherwise compare numerically if (num1[0] != 48) and (num2[0] != 48) num1, num2 = num1.to_i, num2.to_i end case (num1 <=> num2) when -1 then return -1 when 1 then return 1 end when -1 then return -1 when 1 then return 1 end # case end # while # -- strings are naturally equal return 0 end end facets-2.9.3/lib/core/facets/string/shatter.rb0000644000004100000410000000075611714455226021311 0ustar www-datawww-dataclass String # Breaks a string up into an array based on a regular expression. # Similar to scan, but includes the matches. # # s = "

Thisisa test.

" # s.shatter( /\<.*?\>/ ) # # _produces_ # # ["

", "This", "", "is", "", "a test.", "

"] # # CREDIT: Trans def shatter( re ) r = self.gsub( re ){ |s| "\1" + s + "\1" } while r[0,1] == "\1" ; r[0] = '' ; end while r[-1,1] == "\1" ; r[-1] = '' ; end r.split("\1") end end facets-2.9.3/lib/core/facets/string/op_div.rb0000644000004100000410000000035011714455226021105 0ustar www-datawww-dataclass String # Treats +self+ and +path+ as representations # of pathnames, joining thme together as a # single path. # # ('home' / 'trans') #=> 'home/trans' # def /(path) File.join(self, path.to_s) end end facets-2.9.3/lib/core/facets/string/expand_tab.rb0000644000004100000410000000153511714455226021740 0ustar www-datawww-dataclass String # Expands tabs to +n+ spaces. Non-destructive. If +n+ is 0, # then tabs are simply removed. Raises an exception if +n+ # is negative. # # "\t\tHey".expand_tabs(2) #=> " Hey" # # Thanks to GGaramuno for a more efficient algorithm. Very nice. # # CREDIT: Gavin Sinclair, Noah Gibbs, GGaramuno # # TODO: Don't much care for the name String#expand_tabs. # What about a more concise name like #detab? def expand_tabs(n=8) n = n.to_int raise ArgumentError, "n must be >= 0" if n < 0 return gsub(/\t/, "") if n == 0 return gsub(/\t/, " ") if n == 1 str = self.dup while str.gsub!(/^([^\t\n]*)(\t+)/) { |f| val = ( n * $2.size - ($1.size % n) ) $1 << (' ' * val) } end str end # Singular form of #expand_tabs. alias_method :expand_tab, :expand_tabs end facets-2.9.3/lib/core/facets/string/range.rb0000644000004100000410000000220511714455226020722 0ustar www-datawww-dataclass String # Like #index but returns a Range. # # "This is a test!".range('test') #=> (10..13) # # CREDIT: Trans def range(pattern, offset=0) unless Regexp === pattern pattern = Regexp.new(Regexp.escape(pattern.to_s)) end string = self[offset..-1] if md = pattern.match(string) return (md.begin(0)+offset)..(md.end(0)+offset-1) end nil end # Like #index_all but returns an array of Ranges. # # "abc123abc123".range_all('abc') #=> [0..2, 6..8] # # TODO: Add offset ? # # CREDIT: Trans def range_all(pattern, reuse=false) r = []; i = 0 while i < self.length rng = range(pattern, i) if rng r << rng i += reuse ? 1 : rng.end + 1 else break end end r.uniq end # Returns an array of ranges mapping # the characters per line. # # "this\nis\na\ntest".range_of_line # #=> [0..4, 5..7, 8..9, 10..13] # # CREDIT: Trans def range_of_line offset=0; charmap = [] each_line do |line| charmap << (offset..(offset + line.length - 1)) offset += line.length end charmap end end facets-2.9.3/lib/core/facets/string/methodize.rb0000644000004100000410000000101111714455226021610 0ustar www-datawww-dataclass String # Translate a class or module name to a suitable method name. # # "My::CoolClass".methodize #=> "my__cool_class" # def methodize gsub(/([A-Z]+)([A-Z])/,'\1_\2'). gsub(/([a-z])([A-Z])/,'\1_\2'). gsub('/' ,'__'). gsub('::','__'). downcase end # Compare to ActiveSupport's definition: # # gsub(/\//, '__'). # gsub(/::/, '__'). # gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). # gsub(/([a-z\d])([A-Z])/,'\1_\2'). # tr("-", "_"). # downcase # end facets-2.9.3/lib/core/facets/string/snakecase.rb0000644000004100000410000000145511714455226021571 0ustar www-datawww-dataclass String # Underscore a string such that camelcase, dashes and spaces are # replaced by underscores. This is the reverse of {#camelcase}, # albeit not an exact inverse. # # "SnakeCase".snakecase #=> "snake_case" # "Snake-Case".snakecase #=> "snake_case" # "Snake Case".snakecase #=> "snake_case" # "Snake - Case".snakecase #=> "snake_case" # # Note, this method no longer converts `::` to `/`, in that case # use the {#pathize} method instead. def snakecase #gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr('-', '_'). gsub(/\s/, '_'). gsub(/__+/, '_'). downcase end # alias_method :underscore, :snakecase # TODO: Add *separators to #snakecase, like camelcase. end facets-2.9.3/lib/core/facets/string/edit_distance.rb0000644000004100000410000000667711714455226022446 0ustar www-datawww-dataclass String # Levenshtein distance algorithm implementation for Ruby, with UTF-8 support. # # The Levenshtein distance is a measure of how similar two strings s and t are, # calculated as the number of deletions/insertions/substitutions needed to # transform s into t. The greater the distance, the more the strings differ. # # The Levenshtein distance is also sometimes referred to as the # easier-to-pronounce-and-spell 'edit distance'. # # Calculate the Levenshtein distance between two strings +self+ and +str2+. # +self+ and +str2+ should be ASCII, UTF-8, or a one-byte-per character encoding # such as ISO-8859-*. # # The strings will be treated as UTF-8 if $KCODE is set appropriately (i.e. 'u'). # Otherwise, the comparison will be performed byte-by-byte. There is no specific support # for Shift-JIS or EUC strings. # # When using Unicode text, be aware that this algorithm does not perform normalisation. # If there is a possibility of different normalised forms being used, normalisation # should be performed beforehand. # # CREDIT: Paul Battley def edit_distance(str2) str1 = self if $KCODE =~ /^U/i unpack_rule = 'U*' else unpack_rule = 'C*' end s = str1.unpack(unpack_rule) t = str2.unpack(unpack_rule) n = s.length m = t.length return m if (0 == n) return n if (0 == m) d = (0..m).to_a x = nil (0...n).each do |i| e = i+1 (0...m).each do |j| cost = (s[i] == t[j]) ? 0 : 1 x = [ d[j+1] + 1, # insertion e + 1, # deletion d[j] + cost # substitution ].min d[j] = e e = x end d[m] = x end return x end if RUBY_VERSION < '1.9' # Levenshtein distance algorithm implementation for Ruby, with UTF-8 support. # # The Levenshtein distance is a measure of how similar two strings s and t are, # calculated as the number of deletions/insertions/substitutions needed to # transform s into t. The greater the distance, the more the strings differ. # # The Levenshtein distance is also sometimes referred to as the # easier-to-pronounce-and-spell 'edit distance'. # # Calculate the Levenshtein distance between two strings +self+ and +str2+. # +self+ and +str2+ should be ASCII, UTF-8, or a one-byte-per character encoding # such as ISO-8859-*. # # The strings will be treated as UTF-8 if $KCODE is set appropriately (i.e. 'u'). # Otherwise, the comparison will be performed byte-by-byte. There is no specific support # for Shift-JIS or EUC strings. # # When using Unicode text, be aware that this algorithm does not perform normalisation. # If there is a possibility of different normalised forms being used, normalisation # should be performed beforehand. # # CREDIT: Paul Battley def edit_distance(str2) str1 = self if str2.encoding != str1.encoding str2 = str2.encode(str1.encoding.name) end s = str1.codepoints.to_a t = str2.codepoints.to_a n = s.length m = t.length return m if (0 == n) return n if (0 == m) d = (0..m).to_a x = nil (0...n).each do |i| e = i+1 (0...m).each do |j| cost = (s[i] == t[j]) ? 0 : 1 x = [ d[j+1] + 1, # insertion e + 1, # deletion d[j] + cost # substitution ].min d[j] = e e = x end d[m] = x end return x end if RUBY_VERSION >= '1.9' end facets-2.9.3/lib/core/facets/string/align.rb0000644000004100000410000000471211714455226020725 0ustar www-datawww-dataclass String # Alignment method dispatches to #align_right, #align_left # or #align_center, accorging to the first +direction+ parameter. # # s = <<-EOS # This is a test # and # so on # EOS # # s.align(:right, 14) # # _produces_ ... # # This is a test # and # so on # # Returns a String aligned right, left or center. def align(direction, n, sep="\n", c=' ') case direction when :right align_right(n, sep="\n", c=' ') when :left align_left(n, sep="\n", c=' ') when :center align_center(n, sep="\n", c=' ') else raise ArgumentError end end # Align a string to the right. # # The default alignment separation is a new line ("\n"). # This can be changed as can be the padding string which # defaults to a single space (' '). # # s = <<-EOS # This is a test # and # so on # EOS # # s.align_right(14) # # _produces_ ... # # This is a test # and # so on # # CREDIT: Trans def align_right(n, sep="\n", c=' ') return rjust(n.to_i,c.to_s) if sep==nil q = split(sep.to_s).map do |line| line.rjust(n.to_i,c.to_s) end q.join(sep.to_s) end # Align a string to the left. # # The default alignment separation is a new line ("\n"). # This can be changed as can be the padding string which # defaults to a single space (' '). # # s = <<-EOS # This is a test # and # so on # EOS # # s.align_left(20, "\n", '.') # # _produces_ ... # # This is a test...... # and................. # so on............... # # CREDIT: Trans def align_left(n, sep="\n", c=' ') return ljust(n.to_i,c.to_s) if sep==nil q = split(sep.to_s).map do |line| line.strip.ljust(n.to_i,c.to_s) end q.join(sep.to_s) end # Centers each line of a string. # # The default alignment separation is a new line ("\n"). # This can be changed as can be the padding string which # defaults to a single space (' '). # # s = <<-EOS # This is a test # and # so on # EOS # # s.align_center(14) # # _produces_ ... # # This is a test # and # so on # # CREDIT: Trans def align_center(n, sep="\n", c=' ') return center(n.to_i,c.to_s) if sep==nil q = split(sep.to_s).collect { |line| line.center(n.to_i,c.to_s) } q.join(sep.to_s) end end facets-2.9.3/lib/core/facets/string/file.rb0000644000004100000410000000115211714455226020545 0ustar www-datawww-datarequire 'facets/functor' class String # Use fluent notation for making file directives. # # For instance, if we had a file 'foo.txt', # # 'foo.txt'.file.mtime # def file Functor.new(&method(:file_send).to_proc) end private def file_send(op, *a, &b) File.send(op, self, *a, &b) end ## TODO: When no longer needing to support 1.8.6 we can use: ## ## # Use fluent notation for making file directives. ## # ## # 'README.rdoc'.file.mtime ## # ## def file ## f = self ## Functor.new do |op, *a, &b| ## File.send(op, f, *a, &b) ## end ## end end facets-2.9.3/lib/core/facets/string/cleave.rb0000644000004100000410000000113511714455226021066 0ustar www-datawww-dataclass String # Cleave a string. Break a string in two parts at # the nearest whitespace. # # CREDIT: Trans def cleave(threshold=nil, len=nil) l = (len || size / 2) t = threshold || size h1 = self[0...l] h2 = self[l..-1] i1 = h1.rindex(/\s/) || 0 d1 = (i1 - l).abs d2 = h2.index(/\s/) || l i2 = d2 + l d1 = (i1-l).abs d2 = (i2-l).abs if [d1, d2].min > t i = t elsif d1 < d2 i = i1 else i = i2 end #dup.insert(l, "\n").gsub(/^\s+|\s+$/, '') return self[0..i].to_s.strip, self[i+1..-1].to_s.strip end end facets-2.9.3/lib/core/facets/string/acronym.rb0000644000004100000410000000023611714455226021300 0ustar www-datawww-dataclass String # Transform a string into an acronym. # # CREDIT: Robert Fey # def acronym gsub(/(([a-zA-Z0-9])([a-zA-Z0-9])*)./,"\\2") end end facets-2.9.3/lib/core/facets/string/unindent.rb0000644000004100000410000000003711714455226021453 0ustar www-datawww-datarequire 'facets/string/indent' facets-2.9.3/lib/core/facets/string/subtract.rb0000644000004100000410000000011211714455226021450 0ustar www-datawww-data# TODO: Deprecate string/subtract file. # require 'facets/string/op_sub' facets-2.9.3/lib/core/facets/string/end_with.rb0000644000004100000410000000004311714455226021425 0ustar www-datawww-datarequire 'facets/string/start_with' facets-2.9.3/lib/core/facets/string/tabto.rb0000644000004100000410000000043611714455226020743 0ustar www-datawww-datarequire 'facets/string/indent' class String # Preserves relative tabbing. # The first non-empty line ends up with n spaces before nonspace. # # CREDIT: Gavin Sinclair def tabto(n) if self =~ /^( *)\S/ indent(n - $1.length) else self end end end facets-2.9.3/lib/core/facets/string/range_of_line.rb0000644000004100000410000000003611714455226022415 0ustar www-datawww-datarequire 'facets/string/range' facets-2.9.3/lib/core/facets/string/indent.rb0000644000004100000410000000223511714455226021112 0ustar www-datawww-dataclass String # Indent left or right by n spaces. # (This used to be called #tab and aliased as #indent.) # # CREDIT: Gavin Sinclair, Trans, Tyler Rick def indent(n, c=' ') if n >= 0 gsub(/^/, c * n) else gsub(/^#{Regexp.escape(c)}{0,#{-n}}/, "") end end # Equivalent to String#indent, but modifies the receiver in place. def indent!(n, c=' ') replace(indent(n,c)) end # Remove excessive indentation. Useful for multi-line strings embeded in # already indented code. # # <<-END.unindent # ohaie # wurld # END # # Outputs ... # # ohaie # wurld # # Instead of ... # # ohaie # wurld # # CREDIT: Noah Gibbs, mynyml def unindent(size=nil) if size indent(-size) else char = ' ' self.scan(/^[\ \t]*\S/) do |m| if size.nil? || m.size < size size = m.size char = m[0...-1] end end size -= 1 indent(-size, char) end end # Equivalent to String#unindent, but modifies the receiver in place. # # CREDIT: mynyml def unindent! self.replace(self.unindent) end end facets-2.9.3/lib/core/facets/string/lowercase.rb0000644000004100000410000000004211714455226021607 0ustar www-datawww-datarequire 'facets/string/uppercase' facets-2.9.3/lib/core/facets/string/index_all.rb0000644000004100000410000000112311714455226021563 0ustar www-datawww-dataclass String # Like index but returns an array of all index locations. # The reuse flag allows the trailing portion of a match to be # reused for subsquent matches. # # "abcabcabc".index_all('a') #=> [0,3,6] # # "bbb".index_all('bb', false) #=> [0] # "bbb".index_all('bb', true) #=> [0,1] # # TODO: Culd probably be defined for Indexable in general too. def index_all(s, reuse=false) s = Regexp.new(Regexp.escape(s)) unless Regexp===s ia = []; i = 0 while (i = index(s,i)) ia << i i += (reuse ? 1 : $~[0].size) end ia end end facets-2.9.3/lib/core/facets/string/each_word.rb0000644000004100000410000000041111714455226021556 0ustar www-datawww-datarequire 'facets/string/words' class String # Iterate through each word of a string. # # a = [] # # "list of words".each_word { |word| a << word } # # a #=> ['list', 'of', 'words'] # def each_word(&block) words.each(&block) end end facets-2.9.3/lib/core/facets/string/similarity.rb0000644000004100000410000000502011714455226022012 0ustar www-datawww-dataclass String # A fuzzy matching mechanism. Returns a score from 0-1, based # on the number of shared edges. To be effective, the strings # must be of length 2 or greater. # # "Alexsander".similarity("Aleksander") #=> 0.9 # # The way it works: # # 1. Converts each string into a "graph like" object, with edges ... # # "alexsander" -> [ alexsander, alexsand, alexsan ... lexsand ... san ... an, etc ] # "aleksander" -> [ aleksander, aleksand ... etc. ] # # 2. Perform match, then remove any subsets from this matched set (i.e. a hit # on "san" is a subset of a hit on "sander") ... # # Above example, once reduced -> [ ale, sander ] # # 3. See's how many of the matches remain, and calculates a score based # on how many matches, their length, and compare to the length of the # larger of the two words. # # Still a bit rough. Any suggestions for improvement are welcome. # # CREDIT: Derek Lewis. def similarity(str_in) return 0 if str_in == nil return 1 if self == str_in # -- make a graph of each word (okay, its not a true graph, but is similar) graph_A = Array.new graph_B = Array.new # -- "graph" self last = self.length (0..last).each do |ff| loc = self.length break if ff == last - 1 wordB = (1..(last-1)).to_a.reverse! if (wordB != nil) wordB.each do |ss| break if ss == ff graph_A.push( "#{self[ff..ss]}" ) end end end # -- "graph" input string last = str_in.length (0..last).each{ |ff| loc = str_in.length break if ff == last - 1 wordB = (1..(last-1)).to_a.reverse! wordB.each do |ss| break if ss == ff graph_B.push( "#{str_in[ff..ss]}" ) end } # -- count how many of these "graph edges" we have that are the same matches = graph_A & graph_B #-- #matches = Array.new #graph_A.each{ |aa| matches.push(aa) if( graph_B.include?(aa) ) } #++ # -- for eliminating subsets, we want to start with the smallest hits. matches.sort!{|x,y| x.length <=> y.length} # -- eliminate any subsets mclone = matches.dup mclone.each_index do |ii| reg = Regexp.compile( Regexp.escape(mclone[ii]) ) count = 0.0 matches.each{|xx| count += 1 if xx =~ reg} matches.delete(mclone[ii]) if count > 1 end score = 0.0 matches.each{ |mm| score += mm.length } self.length > str_in.length ? largest = self.length : largest = str_in.length return score/largest end end facets-2.9.3/lib/core/facets/string/squish.rb0000644000004100000410000000076511714455226021153 0ustar www-datawww-dataclass String # Returns the string, first removing all whitespace on both ends of # the string, and then changing remaining consecutive whitespace # groups into one space each. # # %{ Multi-line # string }.squish # => "Multi-line string" # # " foo bar \n \t boo".squish # => "foo bar boo" # def squish dup.squish! end # Performs a destructive squish. See String#squish. def squish! strip! gsub!(/\s+/, ' ') self end end facets-2.9.3/lib/core/facets/string/splice.rb0000644000004100000410000000102211714455226021101 0ustar www-datawww-datarequire 'facets/string/store' class String # String#slice is essentially the same as #store. # # a = "HELLO" # a.splice(1, "X") # a #=> "HXLLO" # # But it acts like #slice! when given a single argument. # # a = "HELLO" # a.splice(1) #=> "E" # a #=> "HLLO" # # CREDIT: Trans def splice(idx, sub=nil) if sub store(idx, sub) else case idx when Range slice!(idx) else slice!(idx,1) end end end end facets-2.9.3/lib/core/facets/string/newlines.rb0000644000004100000410000000124311714455226021453 0ustar www-datawww-datarequire "facets/enumerator" class String # Returns an Enumerator for iterating over each # line of the string, void of the termining newline # character, in contrast to #lines which retains it. # # "a\nb\nc".newlines.class.assert == Enumerator # "a\nb\nc".newlines.to_a.assert == %w{a b c} # # a = [] # "a\nb\nc".newlines{|nl| a << nl} # a.assert == %w{a b c} # def newlines(&block) if block scan(/^.*?$/) do |line| block.call(line.chomp) end else str = self Enumerator.new do |output| str.scan(/^.*?$/) do |line| output.yield(line.chomp) end end end end end facets-2.9.3/lib/core/facets/string/quote.rb0000644000004100000410000000376411714455226020776 0ustar www-datawww-dataclass String # Return a new string embraced by given +type+ and +count+ # of quotes. The arguments can be given in any order. # # If no type is given, double quotes are assumed. # # "quote me".quote #=> '"quote me"' # # If no type but a count is given then :mixed is assumed. # # "quote me".quote(1) #=> %q{'quote me'} # "quote me".quote(2) #=> %q{"quote me"} # "quote me".quote(3) #=> %q{'"quote me"'} # # Symbols can be used to describe the type. # # "quote me".quote(:single) #=> %q{'quote me'} # "quote me".quote(:double) #=> %q{"quote me"} # "quote me".quote(:back) #=> %q{`quote me`} # "quote me".quote(:bracket) #=> %q{`quote me'} # # Or the character itself. # # "quote me".quote("'") #=> %q{'quote me'} # "quote me".quote('"') #=> %q{"quote me"} # "quote me".quote("`") #=> %q{`quote me`} # "quote me".quote("`'") #=> %q{`quote me'} # # CREDIT: Trans def quote(type=:double, count=nil) if Integer === type tmp = count count = type type = tmp || :mixed else count ||= 1 end type = type.to_s unless Integer===type case type when "'", 'single', 's', 1 f = "'" * count b = f when '"', 'double', 'd', 2 f = '"' * count b = f when '`', 'back', 'b', -1 f = '`' * count b = f when "`'", 'bracket', 'sb' f = "`" * count b = "'" * count when "'\"", 'mixed', "m", Integer c = (count.to_f / 2).to_i f = '"' * c b = f if count % 2 != 0 f = "'" + f b = b + "'" end else raise ArgumentError, "unrecognized quote type -- #{type}" end "#{f}#{self}#{b}" end # Remove quotes from string. # # "'hi'".unquote #=> "hi" # # CREDIT: Trans def unquote s = self.dup case self[0,1] when "'", '"', '`' s[0] = '' end case self[-1,1] when "'", '"', '`' s[-1] = '' end return s end end facets-2.9.3/lib/core/facets/string/characters.rb0000644000004100000410000000032311714455226021744 0ustar www-datawww-dataclass String # Returns an array of characters. # # "abc".characters.to_a #=> ["a","b","c"] # # TODO: Probably should make this an enumerator. With #scan? def characters split(//) end end facets-2.9.3/lib/core/facets/string/random_binary.rb0000644000004100000410000000030611714455226022452 0ustar www-datawww-dataclass String # Generate a random binary string of +n_bytes+ size. # # CREDIT: Guido De Rosa def self.random_binary(n_bytes) ( Array.new(n_bytes){ rand(0x100) } ).pack('c*') end end facets-2.9.3/lib/core/facets/string/word_wrap.rb0000644000004100000410000000123011714455226021627 0ustar www-datawww-dataclass String # Word wrap a string not exceeding max width. # # "this is a test".word_wrap(4) # # _produces_ ... # # this # is a # test # # This is basic implementation of word wrap, but smart # enough to suffice for most use cases. # # CREDIT: Gavin Kistner, Dayne Broderson # def word_wrap( col_width=80 ) self.dup.word_wrap!( col_width ) end # As with #word_wrap, but modifies the string in place. # # CREDIT: Gavin Kistner, Dayne Broderson # def word_wrap!( col_width=80 ) self.gsub!( /(\S{#{col_width}})(?=\S)/, '\1 ' ) self.gsub!( /(.{1,#{col_width}})(?:\s+|$)/, "\\1\n" ) self end end facets-2.9.3/lib/core/facets/string/bytes.rb0000644000004100000410000000054311714455226020757 0ustar www-datawww-dataclass String unless method_defined?(:bytes) # 1.8.7+ # Upacks string into bytes. # # Note, this is not 100% compatible with 1.8.7+ # which returns an enumerator instead of an array. # def bytes(&blk) if block_given? self.unpack('C*').each(&blk) else self.unpack('C*') end end end end facets-2.9.3/lib/core/facets/string/titlecase.rb0000644000004100000410000000100511714455226021600 0ustar www-datawww-dataclass String # Transform a string into a form that makes for an acceptable title. # # "this is a string".titlecase # #=> "This Is A String" # # @author Eliazar Parra # @author Angelo Lakra (apostrophe fix) def titlecase tr('_', ' '). gsub(/\s+/, ' '). gsub(/\b\w/){ $`[-1,1] == "'" ? $& : $&.upcase } end # Transform a string into a sentence like form. # # "This Is A String".briefcase # #=> "This is a string" # def briefcase titlecase.capitalize end end facets-2.9.3/lib/core/facets/string/to_re.rb0000644000004100000410000000073711714455226020746 0ustar www-datawww-dataclass String # Turns a string into a regular expression. # # "a?".to_re #=> /a?/ # # CREDIT: Trans def to_re(esc=false) Regexp.new((esc ? Regexp.escape(self) : self)) end # Turns a string into a regular expression. # By default it will escape all characters. # Use false argument to turn off escaping. # # "[".to_rx #=> /\[/ # # CREDIT: Trans def to_rx(esc=true) Regexp.new((esc ? Regexp.escape(self) : self)) end end facets-2.9.3/lib/core/facets/string/underscore.rb0000644000004100000410000000004211714455226021774 0ustar www-datawww-datarequire 'facets/string/snakecase' facets-2.9.3/lib/core/facets/string/exclude.rb0000644000004100000410000000014211714455226021255 0ustar www-datawww-dataclass String # The inverse of include?. # def exclude?(str) !include?(str) end end facets-2.9.3/lib/core/facets/string/crypt.rb0000644000004100000410000000077211714455226020776 0ustar www-datawww-dataclass String alias_method :_crypt, :crypt # Common Unix cryptography method. # This adds a default salt to the built-in crypt method. # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # @uncommon # require 'facets/string/crypt' # def crypt(salt=nil) salt ||= ( (rand(26) + (rand(2) == 0 ? 65 : 97) ).chr + (rand(26) + (rand(2) == 0 ? 65 : 97) ).chr ) _crypt(salt) end end facets-2.9.3/lib/core/facets/string/xor.rb0000644000004100000410000000100611714455226020434 0ustar www-datawww-dataclass String # Binary XOR of two strings. # # a = "\000\000\001\001" ^ "\000\001\000\001" # b = "\003\003\003" ^ "\000\001\002" # # a #=> "\000\001\001\000" # b #=> "\003\002\001" # def ^(aString) a = self.unpack('C'*(self.length)) b = aString.unpack('C'*(aString.length)) if (b.length < a.length) (a.length - b.length).times { b << 0 } end xor = "" 0.upto(a.length-1) { |pos| x = a[pos] ^ b[pos] xor << x.chr() } return(xor) end end facets-2.9.3/lib/core/facets/symbol/0000755000004100000410000000000011714455226017301 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/symbol/chomp.rb0000644000004100000410000000052411714455226020735 0ustar www-datawww-dataclass Symbol # Just like String#chomp. # # :ab.chomp(:b) #=> :a # # CREDIT: Trans def chomp(seperator) to_s.chomp(seperator.to_s).to_sym end # Just like String#lchomp. # # :ab.lchomp(:a) #=> :b # # CREDIT: Trans def lchomp(seperator) to_s.reverse.chomp(seperator.to_s).reverse.to_sym end end facets-2.9.3/lib/core/facets/symbol/setter.rb0000644000004100000410000000003611714455226021133 0ustar www-datawww-datarequire 'facets/symbol/plain' facets-2.9.3/lib/core/facets/symbol/query.rb0000644000004100000410000000003611714455226020772 0ustar www-datawww-datarequire 'facets/symbol/plain' facets-2.9.3/lib/core/facets/symbol/writer.rb0000644000004100000410000000003611714455226021141 0ustar www-datawww-datarequire 'facets/symbol/plain' facets-2.9.3/lib/core/facets/symbol/variablize.rb0000644000004100000410000000043011714455226021753 0ustar www-datawww-dataclass Symbol # Prepend an "@" to the beginning of a symbol to make a instance # variable name. This also replaces non-valid characters with underscores. # # :a.variablize #=> :"@a" # def variablize name = to_s.gsub(/\W/, '_') "@#{name}".to_sym end end facets-2.9.3/lib/core/facets/symbol/not.rb0000644000004100000410000000067411714455226020435 0ustar www-datawww-dataclass Symbol # Does a symbol have a "not" sign? # # "friend".to_sym.not? #=> false # "~friend".to_sym.not? #=> true # # CREDIT: Trans def not? self.to_s.slice(0,1) == '~' end # Add a "not" sign to the front of a symbol. # # (~:friend) #=> :"~friend" # # CREDIT: Trans def ~@ if self.to_s.slice(0,1) == '~' "#{self.to_s[1..-1]}".to_sym else "~#{self}".to_sym end end end facets-2.9.3/lib/core/facets/symbol/op_div.rb0000644000004100000410000000061611714455226021111 0ustar www-datawww-datarequire 'facets/string/op_div' class Symbol # Join with _path_ as a file path. # # * path - The path component(s) to append. [#to_s] # # Examples # # (:merb / "string") #=> "merb/string" # (:merb / :symbol) #=> "merb/symbol" # # Returns String of the receiver (as a path string), concatenated # with _path_. def /(path) File.join(to_s, path.to_s) end end facets-2.9.3/lib/core/facets/symbol/succ.rb0000644000004100000410000000067211714455226020570 0ustar www-datawww-dataclass Symbol unless method_defined?(:succ) # 1.9+ TODO: is this right? # Successor method for symobol. This simply converts # the symbol to a string uses String#succ and then # converts it back to a symbol. # # :a.succ #=> :b # # TODO: Make this work more like a simple character dial? def succ(n=1) s = self.to_s n.times do s = s.succ end s.to_sym end end end facets-2.9.3/lib/core/facets/symbol/to_proc.rb0000644000004100000410000000145111714455226021274 0ustar www-datawww-dataclass Symbol unless method_defined?(:to_proc) # 1.8.7+ # Turn a symbol into a proc calling the method to which it refers. # # up = :upcase.to_proc # up.call("hello") #=> 'HELLO' # # More useful is the fact that this allows & # to be used to coerce Symbol into Proc. # # %w{foo bar qux}.map(&:upcase) #=> ["FOO","BAR","QUX"] # [1, 2, 3].inject(&:+) #=> 6 # # TODO: This will be deprecated as of Ruby 1.9, since it will become standard Ruby. # # CREDIT: Florian Gross (orignal), Nobuhiro Imai (current) def to_proc Proc.new{|*args| args.shift.__send__(self, *args)} end # Old Definition... # # def to_proc # proc { |obj, *args| obj.send(self, *args) } # end # end end facets-2.9.3/lib/core/facets/symbol/bang.rb0000644000004100000410000000003611714455226020534 0ustar www-datawww-datarequire 'facets/symbol/plain' facets-2.9.3/lib/core/facets/symbol/thrown.rb0000644000004100000410000000057211714455226021153 0ustar www-datawww-dataclass Symbol # Does the block throw the symbol? # def thrown? catch(self) do begin yield true rescue ArgumentError => err # 1.9 exception false #msg += ", not #{err.message.split(/ /).last}" rescue NameError => err # 1.8 exception false #msg += ", not #{err.name.inspect}" end end end end facets-2.9.3/lib/core/facets/symbol/reader.rb0000644000004100000410000000003611714455226021067 0ustar www-datawww-datarequire 'facets/symbol/plain' facets-2.9.3/lib/core/facets/symbol/plain.rb0000644000004100000410000000164711714455226020741 0ustar www-datawww-dataclass Symbol # Symbol does not end in `!`, `=`, or `?`. # # :a.plain? #=> true # :a?.plain? #=> false # :a!.plain? #=> false # :a=.plain? #=> false # def plain? c = to_s[-1,1] !(c == '=' || c == '?' || c == '!') end # Alias for `#plain?` method. Likely this should have been the original # and only name, but such is life. alias_method :reader?, :plain? # Symbol ends in `=`. # # :a=.setter? #=> true # :a.setter? #=> false # def setter? to_s[-1,1] == '=' end # Alias for `#setter?` method. Likely this should have been the original # and only name, but such is life. alias_method :writer?, :setter? # Symbol ends in `?`. # # :a?.query? #=> true # :a.query? #=> false # def query? to_s[-1,1] == '?' end # Symbol ends in `!`. # # :a!.bang? #=> true # :a.bang? #=> false # def bang? to_s[-1,1] == '!' end end facets-2.9.3/lib/core/facets/symbol/as_s.rb0000644000004100000410000000043211714455226020552 0ustar www-datawww-datarequire 'facets/functor' class Symbol # Convert symbol to string, apply string method and convert # back to symbol via a fluent interface. # # :HELLO.as_s.downcase #=> :hello # def as_s Functor.new do |op, *a| to_s.send(op, *a).to_sym end end end facets-2.9.3/lib/core/facets/symbol/generate.rb0000644000004100000410000000075711714455226021431 0ustar www-datawww-dataclass Symbol # Generate a unique symbol. # # Symbol.generate #=> :"-1" # # If +key+ is given the new symbol will be prefixed with it. # # Symbol.generate(:foo) #=> :"foo-1" # # TODO: Is the generated symbol format acceptable? # # CREDIT: Trans def self.generate(key=nil) key = key.to_sym if key @symbol_generate_counter ||= {} @symbol_generate_counter[key] ||= 0 num = @symbol_generate_counter[key] += 1 ("#{key}-%X" % num).to_sym end end facets-2.9.3/lib/core/facets/method.rb0000644000004100000410000000032211714455226017576 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'method/composition.rb' #require_relative 'method/memoize' # uncommon require_relative 'method/op_mul.rb' require_relative 'method/op_pow.rb' facets-2.9.3/lib/core/facets/nilclass.rb0000644000004100000410000000016311714455226020131 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'nilclass/ergo.rb' require_relative 'nilclass/to_f.rb' facets-2.9.3/lib/core/facets/method/0000755000004100000410000000000011714455226017254 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/method/op_mul.rb0000644000004100000410000000004411714455226021072 0ustar www-datawww-datarequire 'facets/method/composition' facets-2.9.3/lib/core/facets/method/composition.rb0000644000004100000410000000177211714455226022153 0ustar www-datawww-dataclass Method # Method Composition class acts a proxy for composed methods. # # @author Mike Burns class Composition # def initialize(f,g) @f = f @g = g end # def *(h) Composition.new(self, h) end # def ^(n) return self if n < 2 Composition.new(self, self ^ (n-1)) end # def owner @g.owner end # def receiver @g.receiver end # def inspect "#" end # def arity @g.arity end # def to_proc Proc.new {|x| @f.call(*@g.call(*x)) } end # def call(x) @f.call(*@g.call(*x)) end # def [](*x) call(*x) end end # Method composition. # # @author Mike Burns def *(g) Composition.new(self, g) end # Method repetition. # # @author Mike Burns def ^(n) if n < 2 self else Composistion.new(self, self ^ (n-1)) end end end facets-2.9.3/lib/core/facets/method/memoize.rb0000644000004100000410000000061611714455226021251 0ustar www-datawww-dataclass Method # Memoize a method by defining a singleton override. # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # @uncommon # require 'facets/method/memoize' # def memoize(value) singleton = (class << receiver; self; end) singleton.__send__(:define_method, name){ value } end end facets-2.9.3/lib/core/facets/method/op_pow.rb0000644000004100000410000000004411714455226021102 0ustar www-datawww-datarequire 'facets/method/composition' facets-2.9.3/lib/core/facets/proc/0000755000004100000410000000000011714455226016737 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/proc/to_method.rb0000644000004100000410000000161211714455226021246 0ustar www-datawww-datarequire 'facets/proc/bind' require 'facets/kernel/singleton_class' class Proc # Convert Proc to method. # # object = Object.new # # function = lambda { |x| x + 1 } # # function.to_method(object, 'foo') # # object.foo(1) #=> 2 # def to_method(object, name=nil) ##object = object || eval("self", self) block, time = self, Time.now method_name = name || "__bind_#{time.to_i}_#{time.usec}" begin object.singleton_class.class_eval do define_method(method_name, &block) method = instance_method(method_name) remove_method(method_name) unless name method end.bind(object) rescue TypeError object.class.class_eval do define_method(method_name, &block) method = instance_method(method_name) remove_method(method_name) unless name method end.bind(object) end end end facets-2.9.3/lib/core/facets/proc/compose.rb0000644000004100000410000000142111714455226020727 0ustar www-datawww-dataclass Proc # Returns a new proc that is the functional # composition of two procs, in order. # # a = lambda { |x| x + 4 } # b = lambda { |y| y / 2 } # # a.compose(b).call(4) #=> 6 # b.compose(a).call(4) #=> 4 # # CREDIT: Dave def compose(g) raise ArgumentError, "arity count mismatch" unless arity == g.arity lambda{ |*a| self[ *g[*a] ] } end # Operator for Proc#compose and Integer#times_collect/of. # # a = lambda { |x| x + 4 } # b = lambda { |y| y / 2 } # # (a * b).call(4) #=> 6 # (b * a).call(4) #=> 4 # # CREDIT: Dave def *(x) if Integer===x # collect times c = [] x.times{|i| c << call(i)} c else # compose procs lambda{|*a| self[x[*a]]} end end end facets-2.9.3/lib/core/facets/proc/bind_to.rb0000644000004100000410000000052111714455226020700 0ustar www-datawww-dataclass Proc # Bind a procedure to an object. This works # wrapping instance_eval on the Proc object # and then wrapping this in a new Proc. # # a = [1,2,3] # p1 = Proc.new{ join(' ') } # p2 = p1.bind_to(a) # p2.call #=> '1 2 3' # def bind_to(object) Proc.new{object.instance_eval(&self)} end end facets-2.9.3/lib/core/facets/proc/curry.rb0000644000004100000410000000141011714455226020424 0ustar www-datawww-dataclass Proc # Curry Proc object into new Proc object. # # TODO: Utilize Ruby 1.9's #curry method. def curry(*args) if args.empty? idx = (0...arity).to_a else raise ArgumentError, "argument count is greater than prok.arity (#{args.size} > #{arity})" if args.size > arity raise ArgumentError, "arguments must be unique indexes" if args.uniq != args raise ArgumentError, "arguments must be indexes" if args.any?{ |a| !Fixnum===a } idx = (0...arity).to_a idx = args + (idx - args) end pro = self rec = '' idx.each do |i| rec << "proc { |a#{i}| " end rec << "pro[" rec << (0...arity).to_a.collect{|i| "a#{i}"}.join(',') rec << "]" rec << "}" * arity instance_eval rec end end facets-2.9.3/lib/core/facets/proc/bind.rb0000644000004100000410000000115411714455226020201 0ustar www-datawww-datarequire 'facets/kernel/singleton_class' class Proc # Bind a Proc to an object returning a Method. # # NOTE: This version comes from Rails. The old Facets # version used thread.rb, but I no longer think # the implementaiton is thread critical. Please # make a bug report if this proves wrong. # def bind(object) block, time = self, Time.now method_name = "__bind_#{time.to_i}_#{time.usec}" object.singleton_class.class_eval do define_method(method_name, &block) method = instance_method(method_name) remove_method(method_name) method end.bind(object) end end facets-2.9.3/lib/core/facets/proc/partial.rb0000644000004100000410000000112011714455226020712 0ustar www-datawww-datarequire 'facets/na' class Proc # Convert a Proc object into new partial Proc object. # # a = proc { |a,b,c| a+b+c } # b = a.partial(NA,2,NA) # b[1,3] #=> 6 # # Note, the #__ method, which used to be used in stay of NA, # has been deprecated. # #-- # a = proc { |a,b,c| a+b+c } # b = a.partial(__,2,__) # b[1,3] #=> 6 #++ # # This method is similar to Proc#curry. # # CREDT Trans def partial(*args) Proc.new do |*spice| result = args.collect do |a| NA == a ? spice.pop : a end call(*result) end end end facets-2.9.3/lib/core/facets/proc/update.rb0000644000004100000410000000015311714455226020545 0ustar www-datawww-dataclass Proc # Use a Proc as an observable. # # CREDIT: Tim Pease alias_method :update, :call end facets-2.9.3/lib/core/facets/binding.rb0000644000004100000410000000105011714455226017727 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'binding/caller.rb' require_relative 'binding/callstack.rb' require_relative 'binding/call_stack.rb' require_relative 'binding/defined.rb' require_relative 'binding/eval.rb' #require_relative 'binding/local_variables.rb' # uncommon require_relative 'binding/op.rb' require_relative 'binding/op_get.rb' require_relative 'binding/op_set.rb' require_relative 'binding/self.rb' require_relative 'binding/with.rb' require_relative 'binding/__callee__.rb' require_relative 'binding/__method__.rb' facets-2.9.3/lib/core/facets/dir.rb0000644000004100000410000000037211714455226017101 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'dir/ascend.rb' require_relative 'dir/descend.rb' require_relative 'dir/each_child.rb' require_relative 'dir/multiglob.rb' require_relative 'dir/parent.rb' require_relative 'dir/recurse.rb' facets-2.9.3/lib/core/facets/hash/0000755000004100000410000000000011714455226016717 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/hash/except.rb0000644000004100000410000000100411714455226020527 0ustar www-datawww-dataclass Hash # Returns a new hash less the given keys. def except(*less_keys) hash = dup less_keys.each{ |k| hash.delete(k) } hash end # Replaces hash with new hash less the given keys. # This returns the hash of keys removed. # # h = {:a=>1, :b=>2, :c=>3} # h.except!(:a) #=> {:a=>1} # h #=> {:b=>2,:c=>3} # # Returns a Hash of the removed pairs. def except!(*rejected) removed = {} rejected.each{ |k| removed[k] = delete(k) } removed end end facets-2.9.3/lib/core/facets/hash/diff.rb0000644000004100000410000000050111714455226020150 0ustar www-datawww-dataclass Hash # Difference comparison of two hashes. # # h1 = {:a=>1,:b=>2} # h2 = {:a=>1,:b=>3} # # h1.diff(h2) #=> {:b=>2} # h2.diff(h1) #=> {:b=>3} # def diff(hash) h1 = self.dup.delete_if{ |k,v| hash[k] == v } h2 = hash.dup.delete_if{ |k,v| has_key?(k) } h1.merge(h2) end end facets-2.9.3/lib/core/facets/hash/recursively.rb0000644000004100000410000000305411714455226021622 0ustar www-datawww-datarequire 'facets/functor' require 'facets/enumerable/recursively' class Hash # Apply a block to a hash, and recursively apply that block # to each sub-hash: # # h = {:a=>1, :b=>{:x=>1, :y=>2}} # h.recursively.map{ |k,v| [k.to_s, v] } # #=> [["a", 1], ["b", [["y", 2], ["x", 1]]]] # # The recursive iteration can be treated separately from the non-recursive # iteration by passing a block to the #recursive method: # # h = {:a=>1, :b=>{:x=>1, :y=>2}} # h.recursively{ |k,v| [k.to_s, v] }.map{ |k,v| [k.to_s, v.to_s] } # #=> [["a", "1"], ["b", [["y", "2"], ["x", "1"]]]] # def recursively(*types, &block) Recursor.new(self, *types, &block) end class Recursor < Enumerable::Recursor #:nodoc: def method_missing(op, &yld) yld = yld || lambda{ |k,v| [k,v] } # ? to_enum rec = @block || yld #lambda{ |k,v| [k,v] } @enum.__send__(op) do |k,v| case v when String # b/c of 1.8 yld.call(k,v) when *@types res = v.recursively(*@types, &@block).__send__(op,&yld) rec.call(k, res) else yld.call(k,v) end end end end ## TODO: When no longer need 1.8.6 support. =begin def recursively(*types, &block) types = types.empty? ? [self.class] : types Functor.new do |op, &yld| rec = block || yld __send__(op) do |k,v| case v when *types rec.call(k, v.recursively(*types, &block).__send__(op,&yld)) else yld.call(k,v) end end end end =end end facets-2.9.3/lib/core/facets/hash/argumentize.rb0000644000004100000410000000107311714455226021577 0ustar www-datawww-dataclass Hash # Turn a hash into a method arguments. # # h = { :list => [1,2], :base => "HI" } # # Without an argument field. # # h.argumentize #=> [ { :list => [1,2], :base => "HI" } ] # # With an argument field. # # h.argumentize(:list) #=> [ 1, 2, { :base => "HI" } ] # h.argumentize(:base) #=> [ "HI", { :list => [1,2] } ] # def argumentize(args_field=nil) config = dup if args_field args = [config.delete(args_field)].flatten.compact else args = [] end args << config return args end end facets-2.9.3/lib/core/facets/hash/reverse_merge.rb0000644000004100000410000000131011714455226022071 0ustar www-datawww-dataclass Hash # Allows for reverse merging where its the keys in the # calling hash that wins over those in the other_hash. # This is particularly useful for initializing an incoming # option hash with default values: # # def setup(options = {}) # options.reverse_merge! :size => 25, :velocity => 10 # end # # The default :size and :velocity is only set if the +options+ # passed in doesn't already have those keys set. def reverse_merge(other) other.merge(self) end # Inplace form of #reverse_merge. def reverse_merge!(other) replace(reverse_merge(other)) end # Obvious alias for reverse_merge! alias_method :reverse_update, :reverse_merge! end facets-2.9.3/lib/core/facets/hash/autonew.rb0000644000004100000410000000070711714455226020732 0ustar www-datawww-dataclass Hash # Hash which auto initializes it's children. # # h = Hash.autonew # h['s1']['p1'] = 4 # h['s1']['p2'] = 5 # h['s1']['p3'] = 2 # h['s1']['p4'] = 3 # # h #=> {"s1"=>{"p1"=>4, "p4"=>3, "p3"=>2, "p2"=>5}} # # h['s1'].keys.sort # #=> ["p1", "p2", "p3", "p4"] # # CREDIT: Trans, Jan Molic def self.autonew(*args) leet = lambda{ |hsh, key| hsh[key] = new( &leet ) } new(*args,&leet) end end facets-2.9.3/lib/core/facets/hash/select.rb0000644000004100000410000000040511714455226020522 0ustar www-datawww-dataclass Hash unless method_defined?(:select!) # In-place version of Hash#select. The opposite of the built-in # Hash#reject!. # # CREDIT: Gavin Sinclair, Noah Gibbs def select! reject! { |k,v| not yield(k,v) } end end end facets-2.9.3/lib/core/facets/hash/to_struct.rb0000644000004100000410000000052611714455226021275 0ustar www-datawww-dataclass Hash # A method to convert a Hash into a Struct. # # h = {:name=>"Dan","age"=>33,"rank"=>"SrA","grade"=>"E4"} # s = h.to_struct("Foo") # # TODO: Is this robust enough considerd hashes aren't ordered? # # CREDIT: Daniel Berger def to_struct(struct_name) Struct.new(struct_name,*keys).new(*values) end end facets-2.9.3/lib/core/facets/hash/data.rb0000644000004100000410000000144611714455226020162 0ustar www-datawww-datarequire 'facets/functor' class Hash # Access to a hash as if it were an OpenStruct. # # h = {:a=>1, :b=>2} # # h.data.a #=> 1 # h.data.b #=> 2 # h.data.c #=> nil # # h.data.c = 3 # h.data.c #=> 3 # # h.data.a? #=> true # h.data.d? #=> false # # TODO: Change name of Hash#data to something better? # # TODO: Is this really a method worth having? def data this = self Functor.new do |op, *a| case op.to_s when /\=$/ op = op.to_s.chomp('=') this[op] = a.first when /\?$/ op = op.to_s.chomp('?') this.key?(op.to_s) || this.key?(op.to_sym) when /\!$/ op = op.to_s.chomp('!') this[op] # ??? else this[op.to_s] || this[op.to_sym] end end end end facets-2.9.3/lib/core/facets/hash/recurse.rb0000644000004100000410000000120511714455226020712 0ustar www-datawww-dataclass Hash # Apply a block to hash, and recursively apply that block # to each sub-hash or +types+. # # h = {:a=>1, :b=>{:b1=>1, :b2=>2}} # g = h.recurse{|h| h.inject({}){|h,(k,v)| h[k.to_s] = v; h} } # g #=> {"a"=>1, "b"=>{"b1"=>1, "b2"=>2}} # def recurse(*types, &block) types = [self.class] if types.empty? h = inject({}) do |hash, (key, value)| case value when *types hash[key] = value.recurse(*types, &block) else hash[key] = value end hash end yield h end # In place form of #recurse. def recurse!(&block) replace(recurse(&block)) end end facets-2.9.3/lib/core/facets/hash/op_sub.rb0000644000004100000410000000100511714455226020527 0ustar www-datawww-dataclass Hash # Operator for remove hash paris. If another hash is given # the pairs are only removed if both key and value are equal. # If an array is given then matching keys are removed. # # CREDIT: Trans # CREDIT: Xavier Shay (bug fix) def -(other) h = self.dup if other.respond_to?(:to_ary) other.to_ary.each do |k| h.delete(k) end else other.each do |k,v| if h.key?(k) h.delete(k) if v == h[k] end end end h end end facets-2.9.3/lib/core/facets/hash/dearray_values.rb0000644000004100000410000000155511714455226022260 0ustar www-datawww-dataclass Hash # Any array values with be replaced with the first element of the array. # Arrays with no elements will be set to nil. # # h = { :a=>[1], :b=>[1,2], :c=>3, :d=>[] } # h.dearray_values #=> { :a=>1, :b=>1, :c=>3, :d=>nil } # # CREDIT: Trans def dearray_values(index=0) h = {} each do |k,v| case v when Array h[k] = v[index] || v[-1] else h[k] = v end end h end # Any array values with one or no elements will be set to the element # or nil. # # h = { :a=>[1], :b=>[1,2], :c=>3, :d=>[] } # h.dearray_singular_values #=> { :a=>1, :b=>[1,2], :c=>3, :d=>nil } # # CREDIT: Trans def dearray_singular_values h = {} each do |k,v| case v when Array h[k] = (v.size < 2) ? v[0] : v else h[k] = v end end h end end facets-2.9.3/lib/core/facets/hash/deep_merge.rb0000644000004100000410000000116611714455226021344 0ustar www-datawww-dataclass Hash # Same as Hash#merge but recursively merges sub-hashes. def deep_merge(other) hash = self.dup other.each do |key, value| myval = self[key] if value.is_a?(Hash) && myval.is_a?(Hash) hash[key] = myval.deep_merge(value) else hash[key] = value end end hash end # Same as Hash#merge! but recursively merges sub-hashes. def deep_merge!(other) other.each do |key, value| myval = self[key] if value.is_a?(Hash) && myval.is_a?(Hash) myval.deep_merge!(value) else self[key] = value end end self end end facets-2.9.3/lib/core/facets/hash/traverse.rb0000644000004100000410000000213311714455226021076 0ustar www-datawww-dataclass Hash # Returns a new hash created by traversing the hash and its subhashes, # executing the given block on the key and value. The block should # return a 2-element array of the form +[key, value]+. # # h = {"A"=>"A", "B"=>"B", "C"=>{"X"=>"X"}} # # g = h.traverse{ |k,v| [k.downcase, v] } # # g #=> {"a"=>"A", "b"=>"B", "c"=>{"x"=>"X"}} # # NOTE: Hash#traverse is the same as `recursive.graph` and # might be deprecated in the future (if it ever works!) # # CREDIT: Trans def traverse(&block) inject({}) do |h,(k,v)| if Hash === v v = v.traverse(&block) elsif v.respond_to?(:to_hash) v = v.to_hash.traverse(&block) end nk, nv = block.call(k,v) h[nk] = nv h end end # In place version of traverse, which traverses the hash and its # subhashes, executing the given block on the key and value. # # h = { "A"=>"A", "B"=>"B" } # # h.traverse!{ |k,v| [k.downcase, v] } # # h #=> { "a"=>"A", "b"=>"B" } # # CREDIT: Trans def traverse!(&block) replace(traverse(&block)) end end facets-2.9.3/lib/core/facets/hash/insert.rb0000644000004100000410000000041611714455226020551 0ustar www-datawww-dataclass Hash # As with #store but only if the key isn't # already in the hash. # # TODO: Would #store? be a better name? # # CREDIT: Trans def insert(name, value) if key?(name) false else store(name,value) true end end end facets-2.9.3/lib/core/facets/hash/new_with.rb0000644000004100000410000000033511714455226021071 0ustar www-datawww-dataclass Hash # Instantiate a new hash with a default # value determined by the block. # # Hash.new_with{ [] } # # CREDIT: Pit Capitan def self.new_with #:yield: new { |h, k| h[k] = yield } end end facets-2.9.3/lib/core/facets/hash/delete_unless.rb0000644000004100000410000000045311714455226022101 0ustar www-datawww-dataclass Hash # Inverse of #delete_if. # # h = { :a => 1, :b => 2, :c => 3 } # r = h.delete_unless{|k,v| v == 1} # r #=> { :a => 1 } # h #=> { :a => 1 } # # CREDIT: Daniel Schierbeck def delete_unless #:yield: delete_if{ |key, value| ! yield(key, value) } end end facets-2.9.3/lib/core/facets/hash/delete_at.rb0000644000004100000410000000013311714455226021167 0ustar www-datawww-dataclass Hash # Polymorphic with Array#delete_at. alias_method :delete_at, :delete end facets-2.9.3/lib/core/facets/hash/replace_each.rb0000644000004100000410000000033211714455226021635 0ustar www-datawww-dataclass Hash # Same as #update_each, but deletes the key element first. # # CREDIT: Trans def replace_each # :yield: dup.each do |k,v| delete(k) update(yield(k,v)) end self end end facets-2.9.3/lib/core/facets/hash/op_mul.rb0000644000004100000410000000041511714455226020537 0ustar www-datawww-dataclass Hash # Like merge operator '+' but merges in reverse order. # # h1 = {:a=>1} # h2 = {:a=>2, :b=>3} # # (h1 + h2) #=> { :a=>2, :b=>3 } # (h1 * h2) #=> { :a=>1, :b=>3 } # # CREDIT: Trans def *(other) other.merge(self) end end facets-2.9.3/lib/core/facets/hash/count.rb0000644000004100000410000000024211714455226020372 0ustar www-datawww-dataclass Hash # Like Enumerable#count, but counts hash values. # # {:A=>1, :B=>1}.count(1) #=> 2 # def count(value) values.count(value) end end facets-2.9.3/lib/core/facets/hash/to_h.rb0000644000004100000410000000003111714455226020167 0ustar www-datawww-datarequire 'facets/to_hash' facets-2.9.3/lib/core/facets/hash/join.rb0000644000004100000410000000057711714455226020214 0ustar www-datawww-dataclass Hash # Like Array#join but specialized to Hash. # # NOTE: Without Ruby 1.9 this would be difficult to rely on becuase # hashes did not have a strict order. # # CREDIT: Mauricio Fernandez def join(pair_divider='', elem_divider=nil) elem_divider ||= pair_divider s = [] each{ |k,v| s << "#{k}#{pair_divider}#{v}" } s.join(elem_divider) end end facets-2.9.3/lib/core/facets/hash/update_each.rb0000644000004100000410000000053311714455226021507 0ustar www-datawww-dataclass Hash # Iterates through each pair and updates a the hash # in place. This is formally equivalent to #mash! # But does not use #mash to accomplish the task. # Hence #update_each is probably a touch faster. # # CREDIT: Trans def update_each # :yield: dup.each do |k,v| update(yield(k,v)) end self end end facets-2.9.3/lib/core/facets/hash/op_and.rb0000644000004100000410000000127111714455226020505 0ustar www-datawww-dataclass Hash # Hash intersection. Two hashes intersect # when their pairs are equal. # # ({:a=>1,:b=>2} & {:a=>1,:c=>3}) #=> {:a=>1} # # A hash can also be intersected with an array # to intersect keys only. # # ({:a=>1,:b=>2} & [:a,:c]) #=> {:a=>1} # # The later form is similar to #pairs_at. The differ only # in that #pairs_at will return a nil value for a key # not in the hash, but #& will not. # # CREDIT: Trans def &(other) case other when Array k = (keys & other) Hash[*(k.zip(values_at(*k)).flatten)] else x = (to_a & other.to_a).inject([]) do |a, kv| a.concat kv; a end Hash[*x] end end end facets-2.9.3/lib/core/facets/hash/keys.rb0000644000004100000410000000170211714455226020217 0ustar www-datawww-dataclass Hash # Returns true or false whether the hash # contains the given keys. # # h = { :a => 1, :b => 2 } # h.has_keys?( :a ) #=> true # h.has_keys?( :c ) #=> false # # CREDIT: Trans def has_keys?(*check_keys) unknown_keys = check_keys - self.keys return unknown_keys.empty? end alias_method :keys?, :has_keys? # Returns true if the hash contains # _only_ the given keys, otherwise false. # # h = { :a => 1, :b => 2 } # h.has_only_keys?( :a, :b ) #=> true # h.has_only_keys?( :a ) #=> false # # CREDIT: Trans def has_only_keys?(*check_keys) unknown_keys = self.keys - check_keys return unknown_keys.empty? end alias_method :only_keys?, :has_only_keys? # Each with key is like each_pair but reverses the order # the parameters to [value,key] instead of [key,value]. # # CREDIT: Trans def each_with_key( &yld ) each_pair{ |k,v| yld.call(v,k) } end end facets-2.9.3/lib/core/facets/hash/op_add.rb0000644000004100000410000000015011714455226020466 0ustar www-datawww-dataclass Hash # Operator for #merge. # # CREDIT: Trans def +(other) merge(other) end end facets-2.9.3/lib/core/facets/hash/delete_values.rb0000644000004100000410000000152311714455226022066 0ustar www-datawww-dataclass Hash # Minor modification to Ruby's Hash#delete method # allowing it to take multiple keys. # # hsh = { :a => 1, :b => 2 } # hsh.delete_values(1) # hsh #=> { :b => 2 } # # Returns a list of keys of the deleted entries. # # CREDIT: Daniel Schierbeck def delete_values(*values) deleted_keys = [] keys.each do |key| if values.include?(fetch(key)) deleted_keys << key delete(key) end end deleted_keys end # Minor modification to Ruby's Hash#delete method # allowing it to take multiple keys. # # hsh = {:a=>1, :b=>2, :c=>3} # # a, b, c = hsh.delete_values_at(:a, :b, :c) # # [a, b, c] #=> [1, 2, 3] # hsh #=> {} # # CREDIT: Daniel Schierbeck def delete_values_at(*keys, &yld) keys.map{|key| delete(key, &yld) } end end facets-2.9.3/lib/core/facets/hash/delete.rb0000644000004100000410000000022111714455226020501 0ustar www-datawww-data# TODO: should we deprecate hash/delete? require 'facets/hash/delete_at' require 'facets/hash/delete_values' require 'facets/hash/delete_unless' facets-2.9.3/lib/core/facets/hash/to_mod.rb0000644000004100000410000000113011714455226020520 0ustar www-datawww-dataclass Hash # Convert a hash into a module. # # {:a=>1, :b=>2}.to_mod # # Can take a block accepting key, value pairs which will be # evaluated in the context of the module. # # h = {:a=>1, :b=>2} # m = h.to_mod{ |k,v| module_function k } # m.a #=> 1 # m.b #=> 2 # # CREDIT: Jay Fields #-- # TODO: Consider #to_obj? #++ def to_mod(&block) hash = self Module.new do hash.each do |key, value| define_method key do value #.to_object end instance_exec(key, value, &block) if block end end end end facets-2.9.3/lib/core/facets/hash/zip.rb0000644000004100000410000000054011714455226020045 0ustar www-datawww-dataclass Hash # Creates a new hash from two separate arrays, a +keys+ array and # a +values+ array. # # Hash.zip(["a","b","c"], [1,2,3]) # # => { "a"=>1, "b"=>2, "c"=>3 } # # CREDIT: Trans, Ara T. Howard def self.zip(keys,values) # or some better name h = {} keys.size.times{ |i| h[ keys[i] ] = values[i] } h end end facets-2.9.3/lib/core/facets/hash/swap.rb0000644000004100000410000000040711714455226020217 0ustar www-datawww-dataclass Hash # Swap the values of a pair of keys in place. # # {:a=>1,:b=>2}.swap!(:a,:b) #=> {:a=>2,:b=>1} # # CREDIT: Gavin Sinclair def swap!(key1, key2) tmp = self[key1] self[key1] = self[key2] self[key2] = tmp self end end facets-2.9.3/lib/core/facets/hash/at.rb0000644000004100000410000000014711714455226017652 0ustar www-datawww-dataclass Hash # Alias for fetch for greater polymorphism with Array. # alias_method :at, :[] end facets-2.9.3/lib/core/facets/hash/alias.rb0000644000004100000410000000176011714455226020341 0ustar www-datawww-dataclass Hash # Modifies the receiving Hash so that the value previously referred to by # _oldkey_ is also referenced by _newkey_; _oldkey_ is retained in the Hash. # If _oldkey_ does not exist as a key in the Hash, no change is effected. # # Returns a reference to the Hash. # # foo = { :name=>'Gavin', 'wife'=>:Lisa } # foo.alias!('name',:name) #=> { :name=>'Gavin', 'name'=>'Gavin', 'wife'=>:Lisa } # # foo = { :name=>'Gavin', 'wife'=>:Lisa } # foo.alias!('spouse','wife') #=> { :name=>'Gavin', 'wife'=>:Lisa, 'spouse'=>:Lisa } # # foo = { :name=>'Gavin', 'wife'=>:Lisa } # foo.alias!('bar','foo') #=> { :name=>'Gavin', 'wife'=>:Lisa } # # Note that if the _oldkey_ is reassigned, the reference will no longer exist, # and the _newkey_ will remain as it was. # # CREDIT: Gavin Sinclair # # TODO: Rename to #aliaskey or something else. def alias!(newkey, oldkey) self[newkey] = self[oldkey] if self.has_key?(oldkey) self end end facets-2.9.3/lib/core/facets/hash/subset.rb0000644000004100000410000000077211714455226020557 0ustar www-datawww-dataclass Hash # Take a subset of the hash, based on keys given or a block # that evaluates to true for each hash key. # # {'a'=>1, 'b'=>2}.subset('a') #=> {'a'=>1} # {'a'=>1, 'b'=>2}.subset{|k| k == 'a' } #=> {'a'=>1} # # CREDIT: Alexey Petrushin def subset(keys=nil, &block) h = {} if keys self.each do |k, v| h[k] = v if keys.include?(k) end else self.each do |k, v| h[k] = v if block.call(k) end end h end end facets-2.9.3/lib/core/facets/hash/mash.rb0000644000004100000410000000003411714455226020171 0ustar www-datawww-datarequire 'facets/hash/graph' facets-2.9.3/lib/core/facets/hash/to_proc.rb0000644000004100000410000000136211714455226020713 0ustar www-datawww-dataclass Hash # Constructs a Proc object from a hash such that the parameter # of the Proc is assigned the hash keys as attributes. # # c = Class.new do # attr_accessor :a # end # # h = {:a => 1} # o = c.new # h.to_proc.call(o) # o.a #=> 1 # # If +response+ is set to +true+, then assignment will only occur # if receiver responds_to? the writer method. # # CREDIT: Trans def to_proc(response=false) if response lambda do |o| self.each do |k,v| ke = "#{k}=" o.__send__(ke, v) if respond_to?(ke) end end else lambda do |o| self.each do |k,v| ke = "#{k}=" o.__send__(ke, v) end end end end end facets-2.9.3/lib/core/facets/hash/collate.rb0000644000004100000410000000141511714455226020670 0ustar www-datawww-dataclass Hash # Merge the values of this hash with those from another, setting all values # to be arrays representing the values from both hashes. # # { :a=>1, :b=>2 }.collate(:a=>3, :b=>4, :c=>5) # #=> { :a=>[1,3], :b=>[2,4], :c=>[5] } # # @author Trans (rewrite) # @author Tilo Sloboda (bug fixes) # @author Gavin Kistner (original) def collate(other) h = Hash.new (keys + other.keys).each do |key| h[key] = [] end each do |key, value| h[key] << value end other.each do |key, value| h[key] << value end h.each{ |k,v| v.flatten! } h end # The same as #collate, but modifies the receiver in place. def collate!(other_hash) result = collate(other_hash) replace(result) end end facets-2.9.3/lib/core/facets/hash/weave.rb0000644000004100000410000000433011714455226020353 0ustar www-datawww-dataclass Hash # Weave is a very uniqe hash operator. I is designed # to merge to complex hashes in according to sensible, # regular pattern. The effect is akin to inheritance. # # Two hashes are weaved together to produce a new hash. # The two hashes need to be compatible according to the # following rules for each node: ... # # hash, hash => hash (recursive +) # hash, array => error # hash, value => error # array, hash => error # array, array => array + array # array, value => array << value # value, hash => error # value, array => array.unshift(valueB) # value1, value2 => value2 # # Here is a basic example: # # h1 = { :a => 1, :b => [ 1 ], :c => { :x => 1 } } # h2 = { :a => 2, :b => [ 2 ], :c => { :x => 2 } } # # h1.weave(h2) # #=> {:b=>[1, 2], :c=>{:x=>2}, :a=>2} # # Weave follows the most expected pattern of unifying two complex # hashes. It is especially useful for implementing overridable # configuration schemes. # # CREDIT: Thomas Sawyer def weave(h) raise ArgumentError, "Hash expected" unless h.kind_of?(Hash) s = self.clone h.each { |k,node| node_is_hash = node.kind_of?(Hash) node_is_array = node.kind_of?(Array) if s.has_key?(k) self_node_is_hash = s[k].kind_of?(Hash) self_node_is_array = s[k].kind_of?(Array) if self_node_is_hash if node_is_hash s[k] = s[k].weave(node) elsif node_is_array raise ArgumentError, 'Incompatible hash addition' #self[k] = node else raise ArgumentError, 'Incompatible hash addition' #self[k] = node end elsif self_node_is_array if node_is_hash raise ArgumentError, 'Incompatible hash addition' #self[k] = node elsif node_is_array s[k] += node else s[k] << node end else if node_is_hash raise ArgumentError, 'Incompatible hash addition' #self[k] = node elsif node_is_array s[k].unshift( node ) else s[k] = node end end else s[k] = node end } s end end facets-2.9.3/lib/core/facets/hash/inverse.rb0000644000004100000410000000140611714455226020720 0ustar www-datawww-dataclass Hash # Create a "true" inverse hash by storing mutliple values in Arrays. # # h = {"a"=>3, "b"=>3, "c"=>3, "d"=>2, "e"=>9, "f"=>3, "g"=>9} # # h.invert #=> {2=>"d", 3=>"f", 9=>"g"} # h.inverse #=> {2=>"d", 3=>["f", "c", "b", "a"], 9=>["g", "e"]} # h.inverse.inverse #=> {"a"=>3, "b"=>3, "c"=>3, "d"=>2, "e"=>9, "f"=>3, "g"=>9} # # Of course the inverse of the inverse should be the same. # # (h.inverse.inverse == h) #=> true # # CREDIT: Tilo Sloboda def inverse i = Hash.new self.each_pair{ |k,v| if (Array === v) v.each{ |x| i[x] = ( i.has_key?(x) ? [k,i[x]].flatten : k ) } else i[v] = ( i.has_key?(v) ? [k,i[v]].flatten : k ) end } return i end end facets-2.9.3/lib/core/facets/hash/rekey.rb0000644000004100000410000000433211714455226020365 0ustar www-datawww-datarequire 'facets/symbol/to_proc' require 'facets/na' class Hash # TODO: Improve Hash#rekey code!!! # Rekey a hash: # # rekey() # rekey(from_key => to_key, ...) # rekey{|from_key| to_key} # # If a key map is given, then the first key is changed to the second key. # # foo = { :a=>1, :b=>2 } # foo.rekey(:a=>'a') #=> { 'a'=>1, :b=>2 } # foo.rekey(:b=>:x) #=> { :a =>1, :x=>2 } # foo.rekey('foo'=>'bar') #=> { :a =>1, :b=>2 } # # If a block is given, converts all keys in the Hash accroding to the # given block procedure. If the block returns +NA+ for a given key, # then that key will be left intact. # # foo = { :name=>'Gavin', :wife=>:Lisa } # foo.rekey{ |k| k.to_s } #=> { "name"=>"Gavin", "wife"=>:Lisa } # foo #=> { :name =>"Gavin", :wife=>:Lisa } # # If no key map or block is given, then all keys are converted # to Symbols. # # Note that if both a +key_map+ and a block are given, the +key_map+ is # applied first then the block. # # CREDIT: Trans, Gavin Kistner def rekey(key_map=nil, &block) if !(key_map or block) block = lambda{|k| k.to_sym} end key_map ||= {} hash = dup.replace({}) # to keep default_proc (keys - key_map.keys).each do |key| hash[key] = self[key] end key_map.each do |from, to| hash[to] = self[from] if key?(from) end if block hash2 = dup.replace({}) case block.arity when 2 # TODO: is this condition needed? hash.each do |k, v| nk = block.call(k,v) nk = (NA == nk ? k : nk) hash2[nk] = v end else hash.each do |k, v| nk = block.call(k) nk = (NA == nk ? k : nk) hash2[nk] = v end end else hash2 = hash end hash2 end # Synonym for Hash#rekey, but modifies the receiver in place (and returns it). # # foo = { :name=>'Gavin', :wife=>:Lisa } # foo.rekey!{ |k| k.to_s } #=> { "name"=>"Gavin", "wife"=>:Lisa } # foo #=> { "name"=>"Gavin", "wife"=>:Lisa } # # CREDIT: Trans, Gavin Kistner def rekey!(key_map=nil, &block) replace(rekey(key_map, &block)) end end facets-2.9.3/lib/core/facets/hash/symbolize_keys.rb0000644000004100000410000000541611714455226022322 0ustar www-datawww-dataclass Hash # NOTE: These are provided because of their prevalence with Rails users. # We strongly encourage using #rekey instead. # Return a new hash with all keys converted to symbols. With a +select+ block, # limits conversion to only a certain selection of keys. # # foo = { :name=>'Gavin', 'wife'=>:Lisa } # foo.symbolize_keys #=> { :name=>"Gavin", :wife=>:Lisa } # foo #=> { :name =>"Gavin", "wife"=>:Lisa } # # If the key does not respond to #to_sym, then #to_s will be used first. # # For a more versatile method, see #rekey instead. def symbolize_keys(&select) dup.symbolize_keys!(&select) end # Destructively convert all keys to symbols. This is the same as # Hash#symbolize_keys, but modifies the receiver in place and returns it. # With a +select+ block, limits conversion to only selected keys. # # foo = { 'name'=>'Gavin', 'wife'=>:Lisa } # foo.symbolize_keys! #=> { :name=>"Gavin", :wife=>:Lisa } # foo #=> { :name=>"Gavin", :wife=>:Lisa } # # If the key does not respond to #to_sym, then #to_s will be used first. # # For a more versatile method, see #rekey instead. def symbolize_keys!(&select) if select keys.each do |key| if select[key] new_key = (key.to_sym rescue key.to_s.to_sym) self[new_key] = delete(key) end end else keys.each do |key| new_key = (key.to_sym rescue key.to_s.to_sym) self[new_key] = delete(key) end end self end # Return a new hash with all keys converted to strings. Converts all keys # in the Hash to Strings, returning a new Hash. With a +select+ block, # limits conversion to only a certain selection of keys. # # foo = { :name=>'Gavin', :wife=>:Lisa } # foo.stringify_keys #=> { "name"=>"Gavin", "wife"=>:Lisa } # foo #=> { :name =>"Gavin", :wife=>:Lisa } # # This method is considered archaic. Use #rekey instead. def stringify_keys(&select) dup.stringify_keys!(&select) end # Destructively convert all keys to strings. This is the same as # Hash#stringify_keys, but modifies the receiver in place and # returns it. With a +select+ block, limits conversion to only # certain keys. # # foo = { :name=>'Gavin', :wife=>:Lisa } # foo.stringify_keys! #=> { "name"=>"Gavin", "wife"=>:Lisa } # foo #=> { "name"=>"Gavin", "wife"=>:Lisa } # # This method is considered archaic. Use #rekey instead. def stringify_keys!(&select) if select keys.each do |key| if select[key] self[key.to_s] = delete(key) end end else keys.each do |key| self[key.to_s] = delete(key) end end self end end facets-2.9.3/lib/core/facets/hash/update_values.rb0000644000004100000410000000050411714455226022104 0ustar www-datawww-dataclass Hash # Iterate over hash updating just the values. # # h = {:a=>1, :b=>2} # h.update_values{ |v| v + 1 } # h #=> { :a=>2, :b=>3 } # # CREDIT: Trans def update_values #:yield: if block_given? each{ |k,v| store(k, yield(v)) } else to_enum(:update_values) end end end facets-2.9.3/lib/core/facets/hash/op_or.rb0000644000004100000410000000016511714455226020364 0ustar www-datawww-dataclass Hash # Operator for #reverse_merge. # # CREDIT: Trans def |(other) other.merge(self) end end facets-2.9.3/lib/core/facets/hash/stringify_keys.rb0000644000004100000410000000004511714455226022314 0ustar www-datawww-datarequire 'facets/hash/symbolize_keys' facets-2.9.3/lib/core/facets/hash/graph.rb0000644000004100000410000000050511714455226020345 0ustar www-datawww-datarequire 'facets/enumerable/mash' class Hash # In place version of #graph. # # NOTE: Hash#graph! is only useful for Hash. # It is not generally applicable to Enumerable. def graph!(&yld) replace(graph(&yld)) end # Alias for #graph! as an alliteration for "map hash". alias_method :mash!, :graph! end facets-2.9.3/lib/core/facets/hash/update.rb0000644000004100000410000000027211714455226020527 0ustar www-datawww-data# -- for backward compatibility. To be deprecated. require 'facets/hash/op_push' require 'facets/hash/update_each' require 'facets/hash/update_keys' require 'facets/hash/update_values' facets-2.9.3/lib/core/facets/hash/to_options.rb0000644000004100000410000000004511714455226021440 0ustar www-datawww-datarequire 'facets/hash/symbolize_keys' facets-2.9.3/lib/core/facets/hash/slice.rb0000644000004100000410000000171211714455226020344 0ustar www-datawww-dataclass Hash # Returns a new hash with only the given keys. # # h = {:a=>1, :b=>2} # h.slice(:a) #=> {:a=>1} # def slice(*keep_keys) hash = {} keep_keys.each do |key| hash[key] = fetch(key) end hash end # Replaces hash with a new hash having only the given keys. # This return the hash of keys removed. # # h = {:a=>1, :b=>2} # h.slice!(:a) #=> {:b=>2} # h #=> {:a=>1} # # Returns a Hash of the removed pairs. def slice!(*keep_keys) rejected = keys - keep_keys removed = {} rejected.each{ |k| removed[k] = delete(k) } removed end end # NOTE: ActiveSupport defines this method but adds a check for #convert_key. # If the method is defined, then it converts the keys with it. However # it doesn't look to be supported by all Hash methods, just # HashWithIndifferentAccess. I'm not so sure support for this kind of # thing is appropriate for Facets. facets-2.9.3/lib/core/facets/hash/op_push.rb0000644000004100000410000000036411714455226020724 0ustar www-datawww-dataclass Hash # Can be used like update, or passed # as two-element [key,value] array. # # CREDIT: Trans def <<(other) if other.respond_to?(:to_ary) self.store(*other) else update(other) end self end end facets-2.9.3/lib/core/facets/hash/update_keys.rb0000644000004100000410000000061011714455226021556 0ustar www-datawww-dataclass Hash # Iterate over hash updating just the keys. # # h = {:a=>1, :b=>2} # h.update_keys{ |k| "#{k}!" } # h #=> { "a!"=>1, "b!"=>2 } # # @author Trans # @author Evgeniy Dolzhenko (bug fix) def update_keys #:yield: if block_given? keys.each { |old_key| store(yield(old_key), delete(old_key)) } else to_enum(:update_keys) end end end facets-2.9.3/lib/core/facets/hash/url_params.rb0000644000004100000410000000062611714455226021415 0ustar www-datawww-dataclass Hash # Allows for taking a hash and turning it into CGI params # Since 1.8.x does not have ordered hashes the params might not # be ordered. # # @todo Hash#url_params may require some URL escaping. # # @author Matt Kirk def url_params map do |k,v| if v.respond_to?(:join) "#{k}=#{v.join(",")}" else "#{k}=#{v}" end end.join("&") end end facets-2.9.3/lib/core/facets/hash/op.rb0000644000004100000410000000025711714455226017666 0ustar www-datawww-datarequire 'facets/hash/op_and' require 'facets/hash/op_or' require 'facets/hash/op_add' require 'facets/hash/op_sub' require 'facets/hash/op_mul' require 'facets/hash/op_push' facets-2.9.3/lib/core/facets/dir/0000755000004100000410000000000011714455226016552 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/dir/recurse.rb0000644000004100000410000000150311714455226020546 0ustar www-datawww-dataclass Dir # Recursively scan a directory and pass each file to the given block. # # Dir.recurse('.') do |path| # # ... # end # # CREDIT: George Moschovitis # # TODO: If fully compatible, reimplement as alias of Find.find, # or just copy and paste Find.find code here if it looks more robust. # def self.recurse(path='.', &block) list = [] stoplist = ['.', '..'] Dir.foreach(path) do |f| next if stoplist.include?(f) filename = (path == '.' ? f : path + '/' + f) list << filename block.call(filename) if block if FileTest.directory?(filename) and not FileTest.symlink?(filename) list.concat(Dir.recurse(filename, &block)) end end list end # Same as Dir#recurse. def self.ls_r(path='.', &block) recurse(path, &block) end end facets-2.9.3/lib/core/facets/dir/descend.rb0000644000004100000410000000003411714455226020501 0ustar www-datawww-datarequire 'facets/dir/ascend' facets-2.9.3/lib/core/facets/dir/ascend.rb0000644000004100000410000000176611714455226020346 0ustar www-datawww-dataclass Dir # TODO: Make instance method versions ? # Ascend a directory path. # # a = [] # # Dir.ascend("/var/log") do |path| # a << path # end # # a #=> ['/var/log', '/var', '/'] # # CREDIT: Daniel Berger, Jeffrey Schwab # # TODO: make it work with windows too # use FileTest.root? def self.ascend(dir, inclusive=true, &blk) dir = dir.dup blk.call(dir) if inclusive ri = dir.rindex('/') while ri dir = dir.slice(0...ri) if dir == "" blk.call('/') ; break end blk.call( dir ) ri = dir.rindex('/') end end # Descend a directory path. # # d = [] # # Dir.descend("/var/log") do |path| # d << path # end # # d #=> ['/', '/var', '/var/log'] # # CREDIT: Daniel Berger, Jeffrey Schwab def self.descend(path) #:yield: paths = path.split('/') paths.size.times do |n| pth = File.join(*paths[0..n]) pth = "/" if pth == "" yield(pth) end end end facets-2.9.3/lib/core/facets/dir/parent.rb0000644000004100000410000000044611714455226020374 0ustar www-datawww-dataclass Dir # Is a path parental to another? # # Dir.parent?('parent', 'parent/child') #=> true # # TODO: Needs improvement. # # TODO: Instance version? def self.parent?(parent_path, child_path) %r|^#{Regexp.escape(parent_path)}| =~ child_path ? true : false end end facets-2.9.3/lib/core/facets/dir/multiglob.rb0000644000004100000410000000417311714455226021102 0ustar www-datawww-dataclass Dir # Like +glob+ but can take multiple patterns. # # Dir.multiglob('tmp/*.rb', 'tmp/*.py') # # Rather then constants for options multiglob accepts a trailing options # hash of symbol keys... # # :noescape File::FNM_NOESCAPE # :casefold File::FNM_CASEFOLD # :pathname File::FNM_PATHNAME # :dotmatch File::FNM_DOTMATCH # :strict File::FNM_PATHNAME && File::FNM_DOTMATCH # # It also has an option for recurse... # # :recurse Recurively include contents of directories. # # For example # # Dir.multiglob('tmp/*', :recurse => true) # # would have the same result as # # Dir.multiglob('tmp/**/*') # def self.multiglob(*patterns) options = (Hash === patterns.last ? patterns.pop : {}) if options.delete(:recurse) ##patterns += patterns.collect{ |f| File.join(f, '**', '**') } multiglob_r(*patterns) end bitflags = 0 bitflags |= File::FNM_NOESCAPE if options[:noescape] bitflags |= File::FNM_CASEFOLD if options[:casefold] bitflags |= File::FNM_PATHNAME if options[:pathname] or options[:strict] bitflags |= File::FNM_DOTMATCH if options[:dotmatch] or options[:strict] patterns = [patterns].flatten.compact if options[:recurse] patterns += patterns.collect{ |f| File.join(f, '**', '**') } end files = [] files += patterns.collect{ |pattern| Dir.glob(pattern, bitflags) }.flatten.uniq return files end # The same as +multiglob+, but recusively includes directories. # # Dir.multiglob_r('tmp') # # is equivalent to # # Dir.multiglob('tmp', :recurse=>true) # # The effect of which is # # Dir.multiglob('tmp', 'tmp/**/**') # def self.multiglob_r(*patterns) options = Hash === patterns.last ? patterns.pop : {} matches = multiglob(*patterns) directories = matches.select{ |m| File.directory?(m) } matches += directories.map{ |d| multiglob_r(File.join(d, '**'), options) }.flatten matches.uniq ##options = (Hash === patterns.last ? patterns.pop : {}) ##options[:recurse] = true ##patterns << options ##multiglob(*patterns) end end facets-2.9.3/lib/core/facets/dir/each_child.rb0000644000004100000410000000060311714455226021141 0ustar www-datawww-dataclass Dir # Like #each, except the "." and ".." special files are ignored. # You can use +ignore+ to override '.' and '..' and ignore # other entries via a exact match or regular expression. # # CREDIT: Tyler Rick def each_child(*ignore) ignore = ['.', '..'] if ignore.empty? each do |file| yield file unless ignore.any?{ |i| i === file } end end end facets-2.9.3/lib/core/facets/unboundmethod.rb0000644000004100000410000000020211714455226021166 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'unboundmethod/arguments.rb' require_relative 'unboundmethod/name.rb' facets-2.9.3/lib/core/facets/numeric.rb0000644000004100000410000000060211714455226017761 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'numeric/approx.rb' require_relative 'numeric/distance.rb' require_relative 'numeric/length.rb' require_relative 'numeric/negative.rb' require_relative 'numeric/positive.rb' require_relative 'numeric/round.rb' require_relative 'numeric/round_at.rb' require_relative 'numeric/round_to.rb' require_relative 'numeric/spacing.rb' facets-2.9.3/lib/core/facets/denumerable.rb0000644000004100000410000000263011714455226020605 0ustar www-datawww-datarequire 'facets/enumerator' #require 'facets/enumerable/take' # Classes which include Denumerable will get versions of map, # select, and so on, which return a Denumerator, so that they # work horizontally without creating intermediate arrays. # # @author Brian Candler # @author Trans module Denumerable # def map Denumerator.new do |output| each do |*input| output.yield yield(*input) end end end alias :collect :map # def select Denumerator.new do |output| each do |*input| output.yield(*input) if yield(*input) end end end alias :find_all :select # def reject Denumerator.new do |output| each do |*input| output.yield(*input) unless yield(*input) end end end # Limit to the first n items in the list def take(n) Denumerator.new do |output| count = 0 each do |*input| break if count >= n output.yield(*input) count += 1 end end end # Skip the first n items in the list def skip(n) Denumerator.new do |output| count = 0 each do |*input| output.yield(*input) if count >= n count += 1 end end end # TODO: add more methods, e.g. grep, take_while etc. end # = Denumerator # # A class like Enumerator, but which has 'lazy' versions of map, select etc. # class Denumerator < Enumerator include Denumerable end facets-2.9.3/lib/core/facets/exception.rb0000644000004100000410000000024211714455226020315 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'exception/detail.rb' require_relative 'exception/raised.rb' require_relative 'exception/suppress.rb' facets-2.9.3/lib/core/facets/string.rb0000644000004100000410000000510711714455226017632 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'string/acronym.rb' require_relative 'string/align.rb' require_relative 'string/bracket.rb' require_relative 'string/bytes.rb' require_relative 'string/camelcase.rb' require_relative 'string/capitalized.rb' require_relative 'string/characters.rb' require_relative 'string/cleanlines.rb' require_relative 'string/cleave.rb' require_relative 'string/cmp.rb' require_relative 'string/compress_lines.rb' #require_relative 'string/crypt.rb' # uncommon require_relative 'string/divide.rb' require_relative 'string/each_char.rb' require_relative 'string/each_word.rb' require_relative 'string/edit_distance.rb' require_relative 'string/end_with.rb' require_relative 'string/exclude.rb' require_relative 'string/expand_tab.rb' require_relative 'string/file.rb' require_relative 'string/fold.rb' require_relative 'string/indent.rb' require_relative 'string/index_all.rb' require_relative 'string/interpolate.rb' require_relative 'string/lchomp.rb' require_relative 'string/lines.rb' require_relative 'string/line_wrap.rb' require_relative 'string/lowercase.rb' require_relative 'string/margin.rb' require_relative 'string/methodize.rb' require_relative 'string/modulize.rb' require_relative 'string/mscan.rb' require_relative 'string/natcmp.rb' require_relative 'string/nchar.rb' require_relative 'string/newlines.rb' require_relative 'string/op_div.rb' require_relative 'string/op_sub.rb' require_relative 'string/outdent.rb' require_relative 'string/pathize.rb' require_relative 'string/quote.rb' require_relative 'string/random_binary.rb' require_relative 'string/range.rb' require_relative 'string/range_all.rb' require_relative 'string/range_of_line.rb' require_relative 'string/rewrite.rb' #require_relative 'integer/roman.rb' # uncommon require_relative 'string/shatter.rb' require_relative 'string/similarity.rb' require_relative 'string/snakecase.rb' require_relative 'string/splice.rb' require_relative 'string/squish.rb' require_relative 'string/start_with.rb' require_relative 'string/store.rb' require_relative 'string/subtract.rb' require_relative 'string/tab.rb' require_relative 'string/tabto.rb' require_relative 'string/titlecase.rb' require_relative 'string/to_re.rb' require_relative 'string/unbracket.rb' require_relative 'string/underscore.rb' require_relative 'string/unfold.rb' require_relative 'string/unindent.rb' require_relative 'string/unquote.rb' require_relative 'string/uppercase.rb' require_relative 'string/variablize.rb' require_relative 'string/words.rb' require_relative 'string/word_wrap.rb' require_relative 'string/xor.rb' facets-2.9.3/lib/core/facets/kernel/0000755000004100000410000000000011714455226017254 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/kernel/call_stack.rb0000644000004100000410000000230011714455226021674 0ustar www-datawww-datamodule Kernel alias_method :pp_callstack, :caller alias_method :pp_call_stack, :caller # Parse a caller string and break it into its components, # returning an array composed of: # # * file (String) # * lineno (Integer) # * method (Symbol) # # For example, from irb # # call_stack(1) # # _produces_ ... # # [["(irb)", 2, :irb_binding], # ["/usr/lib/ruby/1.8/irb/workspace.rb", 52, :irb_binding], # ["/usr/lib/ruby/1.8/irb/workspace.rb", 52, nil]] # # Note: If the user decides to redefine caller() to output data # in a different format, _prior_ to requiring this, then the # results will be indeterminate. # # CREDIT: Trans def call_stack(level = 1) call_str_array = pp_call_stack(level) stack = [] call_str_array.each{ |call_str| file, lineno, method = call_str.split(':') if method =~ /in `(.*)'/ then method = $1.intern() end stack << [file, lineno.to_i, method] } stack end alias_method :callstack, :call_stack end class Binding # Returns the call stack, in array format. def call_stack(level=1) eval( "callstack( #{level} )" ) end alias_method :callstack, :call_stack end facets-2.9.3/lib/core/facets/kernel/blank.rb0000644000004100000410000000272011714455226020671 0ustar www-datawww-datamodule Kernel # An object is blank if it's nil, empty, or a whitespace string. # For example, "", " ", nil, [], and {} are blank. # # This simplifies... # # if !address.nil? && !address.empty? # # to... # # if !address.blank? # def blank? return empty? if respond_to?(:empty?) !self end # An object is present if it's not blank. def present? !blank? end # Returns object if it's #present? otherwise returns nil. # object.presence is equivalent to object.present? ? object : nil. # # This is handy for any representation of objects where blank is the same # as not present at all. For example, this simplifies a common check for # HTTP POST/query parameters... # # state = params[:state] if params[:state].present? # country = params[:country] if params[:country].present? # region = state || country || 'US' # # becomes... # # region = params[:state].presence || params[:country].presence || 'US' # def presence self if present? end end class NilClass def blank? true end end class FalseClass def blank? true end end class TrueClass def blank? false end end class Array alias_method :blank?, :empty? end class Hash alias_method :blank?, :empty? end class String # Is this string just whitespace? # # "abc".blank? #=> false # " ".blank? #=> true def blank? /\S/ !~ self end end class Numeric def blank? false end end facets-2.9.3/lib/core/facets/kernel/in.rb0000644000004100000410000000026111714455226020206 0ustar www-datawww-datamodule Kernel # Is self included in other? # # 5.in?(0..10) #=> true # 5.in?([0,1,2,3]) #=> false # def in?(other) other.include?(self) end end facets-2.9.3/lib/core/facets/kernel/maybe.rb0000644000004100000410000000047511714455226020704 0ustar www-datawww-datamodule Kernel # Random generator that returns true or false. # Can also take a block that has a 50/50 chance # to being executed... # # maybe #=> true # maybe #=> false # def maybe(chance = 0.5, &block) if block yield if rand < chance else rand < chance end end end facets-2.9.3/lib/core/facets/kernel/load_all.rb0000644000004100000410000000004411714455226021346 0ustar www-datawww-datarequire 'facets/kernel/require_all' facets-2.9.3/lib/core/facets/kernel/silence.rb0000644000004100000410000000312311714455226021222 0ustar www-datawww-datamodule Kernel # Silence a stream and/or warnings... # # silence(:stdout) do # puts "won't see me" # end # # Supported +streams+ are +stderr+, +stdout+, +verbose+, +debug+, # and +warnings+, which is the same as +verbose+. You can also # use the actual streams, STDERR and STDOUT. def silence(*streams) #:yield: streams = streams.map do |stream| case stream when :stderr STDERR when :stdout STDOUT else stream end end if streams.empty? yield else silence_stream(*streams){ yield } end end # Just like silence_stream, but will default to # STDOUT, STDERR if no streams are given. def silently(*streams) #:yeild: streams = [STDOUT, STDERR] if streams.empty? silence_stream(*streams){ yield } end # Silences any stream for the duration of the block... # # silence_stream(STDOUT) do # puts 'This will never be seen' # end # # puts 'But this will' # # CREDIT: David Heinemeier Hansson def silence_stream(*streams) #:yeild: on_hold = streams.collect{ |stream| stream.dup } streams.each do |stream| stream.reopen(RUBY_PLATFORM =~ /mswin/ ? 'NUL:' : '/dev/null') stream.sync = true end yield ensure streams.each_with_index do |stream, i| stream.reopen(on_hold[i]) end end # Equivalent to `silence_stream(STDERR)`. def silence_stderr #:yeild: silence_stream(STDERR) { yield } end # Equivalent to `silence_stream(STDOUT)`. def silence_stdout #:yeild: silence_stream(STDOUT) { yield } end end facets-2.9.3/lib/core/facets/kernel/enable_warnings.rb0000644000004100000410000000005111714455226022733 0ustar www-datawww-datarequire 'facets/kernel/disable_warnings' facets-2.9.3/lib/core/facets/kernel/object_class.rb0000644000004100000410000000025211714455226022233 0ustar www-datawww-datamodule Kernel # Defines object_classas an alias of class. # This is an alternative to __class__, akin to # #object_id. alias_method :object_class, :class end facets-2.9.3/lib/core/facets/kernel/returning.rb0000644000004100000410000000123711714455226021621 0ustar www-datawww-datamodule Kernel # A Ruby-ized realization of the K combinator. # # book_class = Struct.new(:title, :author) # # book = returning book_class.new do |book| # book.title = "Imperium" # book.author = "Ulick Varange" # end # # book.class #=> book_class # # Technically, #returning probably should force the return of # the stated object irregardless of any return statements that # might appear within it's block. This might differentiate # #returning from #with, however it also would require # implementation in Ruby itself. # # CREDIT: Mikael Brockman def returning(obj=self) #:yield: yield obj obj end end facets-2.9.3/lib/core/facets/kernel/attr_singleton.rb0000644000004100000410000000252711714455226022643 0ustar www-datawww-datamodule Kernel # Creates singleton attr_readers. # # obj = Object.new # # obj.attr_singleton_reader :x, :y # # attr_singleton_reader :x, :y # # CREDIT: Trans def attr_singleton_reader(*args) #h, a = *args.partition{|a| Hash===a} (class << self ; self ; end).send( :attr_reader, *args ) #(class << self ; self ; end).send( :attr_reader, *h.keys ) #h.each { |k,v| instance_variable_set("@#{k}", v) } end # Create singleton attr_writers. # # obj = Object.new # # obj.attr_singleton_writer :x, :y # # obj.x = 3 # obj.y = 4 # # CREDIT: Trans def attr_singleton_writer(*args) #h, a = *args.partition{|a| Hash===a} (class << self ; self ; end).send( :attr_writer, *args ) #(class << self ; self ; end).send( :attr_writer, *h.keys ) #h.each { |k,v| instance_variable_set("@#{k}", v) } end # Create singleton attr_accessors. # # obj = Object.new # # obj.attr_singleton_accessor :x, :y # # obj.x = 3 # obj.y = 4 # obj.x #=> 3 # obj.y #=> 4 # # CREDIT: Trans def attr_singleton_accessor(*args) #h, a = *args.partition{|a| Hash===a} (class << self ; self ; end).send( :attr_accessor, *args ) #(class << self ; self ; end).send( :attr_accessor, *h.keys ) #h.each { |k,v| instance_variable_set("@#{k}", v) } end end facets-2.9.3/lib/core/facets/kernel/demo.rb0000644000004100000410000000146211714455226020530 0ustar www-datawww-datamodule Kernel # TODO: Is there a way to do this without the eval string in block? # Preferably just a block and no string. # For debugging and showing examples. Currently this # takes an argument of a string in a block... # # demo {%{ a = [1,2,3] }} # demo {%{ a.slice(1,2) }} # demo {%{ a.map { |x| x**3 } }} # # produces ... # # a = [1,2,3] #=> [1, 2, 3] # a.slice(1,2) #=> [2, 3] # a.map { |x| x**3 } #=> [1, 8, 27] # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # @uncommon # require 'facets/kernel/demo' # def demo(out=$stdout,&block) out << sprintf("%-25s#=> %s\n", expr = block.call, eval(expr, block.binding).inspect) end end facets-2.9.3/lib/core/facets/kernel/instance_send.rb0000644000004100000410000000012011714455226022407 0ustar www-datawww-datamodule Kernel # Private send. alias_method :instance_send, :__send__ end facets-2.9.3/lib/core/facets/kernel/y.rb0000644000004100000410000000067611714455226020062 0ustar www-datawww-datamodule Kernel # Y-combinator. # # f = Y do |n, acc, &b| # n < 2 ? acc : b.(n-1, n * acc) # end # # f.call(5, 1) #=> 120 # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # CREDIT: Michael Fellinger # # @uncommon # require 'facets/kernel/y' # def Y(*args, &block) y = lambda{|*args| block.call(*args, &y) } end end facets-2.9.3/lib/core/facets/kernel/meta_class.rb0000644000004100000410000000064111714455226021715 0ustar www-datawww-datamodule Kernel # Easy access to an object's "special" class, otherwise known as it's # singleton class, eigenclass, adhoc class or object-qua-class. # def meta_class(&block) if block_given? (class << self; self; end).class_eval(&block) else (class << self; self; end) end end # The non-underscored form of #meta_class if faily common. alias_method :metaclass, :meta_class end facets-2.9.3/lib/core/facets/kernel/present.rb0000644000004100000410000000003611714455226021260 0ustar www-datawww-datarequire 'facets/kernel/blank' facets-2.9.3/lib/core/facets/kernel/load_relative.rb0000644000004100000410000000005111714455226022407 0ustar www-datawww-datarequire 'facets/kernel/require_relative' facets-2.9.3/lib/core/facets/kernel/eigenclass.rb0000644000004100000410000000124711714455226021722 0ustar www-datawww-datamodule Kernel # During this trying time when no one can get their # techie catchwords to stick to the refrigerator no # matter how hard they slap it with the enchanted # magnetic spatula, it’s good to know that the # contrived phrases really do fly, graceful and # unclasped and bearing north toward chilled shrimp. # I know what my Hallowe’en pumpkin is going to say. # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # CREDIT: WhyTheLuckyStiff # # @uncommon # require 'facets/kernel/eigenclass' # def eigenclass (class << self; self; end) end end facets-2.9.3/lib/core/facets/kernel/disable_warnings.rb0000644000004100000410000000062211714455226023114 0ustar www-datawww-datamodule Kernel # # CREDIT: Trans def disable_warnings #:yield: verbose, $VERBOSE = $VERBOSE, nil yield ensure $VERBOSE = verbose end # DEPRECATE: Use #disable_warnings instead. alias_method :silence_warnings, :disable_warnings # # CREDIT: Trans def enable_warnings #:yield: verbose, $VERBOSE = $VERBOSE, true yield ensure $VERBOSE = verbose end end facets-2.9.3/lib/core/facets/kernel/__get__.rb0000644000004100000410000000052511714455226021156 0ustar www-datawww-datamodule Kernel # Shadow method for instance_variable_get. def __get__(ivar) #ivar = "@#{ivar}" unless ivar.to_s[0,1] == '@' instance_variable_get(ivar) end # Shadow method for instance_variable_set. def __set__(ivar, val) #ivar = "@#{ivar}" unless ivar.to_s[0,1] == '@' instance_variable_set(ivar, val) end end facets-2.9.3/lib/core/facets/kernel/silence_warnings.rb0000644000004100000410000000005111714455226023127 0ustar www-datawww-datarequire 'facets/kernel/disable_warnings' facets-2.9.3/lib/core/facets/kernel/tap.rb0000644000004100000410000000203411714455226020364 0ustar www-datawww-datamodule Kernel unless method_defined?(:tap) # 1.8.7+ # The tap K-Combinator. This yields self -and- returns self. # # Note, Ruby 1.9+ does not support the zero arity #instance_eval # variation so it has been deprecated. def tap #:yield: yield(self) self end #-- # == Old definition # # # def tap #:yield: # if block_given? # b.arity == 1 ? yield(self) : instance_eval(&b) # end # return self # end # # == Future definition? # # This is a consideration for a future #tap using Functor: # # require 'facets/functor' # # def tap(&b) # if block_given? # b.arity == 1 ? yield(self) : instance_eval(&b) # self # else # Functor.new{ |op, *args| self.send(op, *args); self } # end # end # # It would allow a single call, before returning the original. # However there are not very many useful things you can do with # that. #++ end end facets-2.9.3/lib/core/facets/kernel/constant.rb0000644000004100000410000000115011714455226021427 0ustar www-datawww-datamodule Kernel # This is similar to +Module#const_get+ but is accessible at all levels, # and, unlike +const_get+, can handle module hierarchy. # # constant("Fixnum") # => Fixnum # constant(:Fixnum) # => Fixnum # # constant("Process::Sys") # => Process::Sys # constant("Regexp::MULTILINE") # => 4 # # CREDIT: Trans def constant(const) const = const.to_s.dup base = const.sub!(/^::/, '') ? Object : ( self.kind_of?(Module) ? self : self.class ) const.split(/::/).inject(base){ |mod, name| mod.const_get(name) } end end facets-2.9.3/lib/core/facets/kernel/extend.rb0000644000004100000410000000107611714455226021074 0ustar www-datawww-datamodule Kernel alias_method :_extend, :extend private :_extend # Extend an object with a module. # # If a block is given, it will be evaluated into an anonymous # module and used to extend the object. # # obj = Object.new # # obj.extend do # def foo; "foo"; end # end # # obj.foo #=> "foo" # # NOTE: This is one of the few core overrides in Facets. # # @author Trans # @author Marco Otte-Witte (bug fix) def extend(*mod, &blk) _extend(*mod) unless mod.empty? _extend Module.new(&blk) if blk self end end facets-2.9.3/lib/core/facets/kernel/identical.rb0000644000004100000410000000006711714455226021540 0ustar www-datawww-datamodule Kernel alias_method :identical?, :equal? end facets-2.9.3/lib/core/facets/kernel/require_relative.rb0000644000004100000410000000252311714455226023152 0ustar www-datawww-datamodule Kernel unless private_method_defined?(:require_relative) # 1.9 # Require file from same dir as calling script... # # require_local 'myscript' # # CREDIT: Paul Brannan, Pragmatic Programmers # def require_relative(relative_feature) c = caller.first fail "Can't parse #{c}" unless c.rindex(/:\d+(:in `.*')?$/) file = $` # File.dirname(c) if /\A\((.*)\)/ =~ file # eval, etc. raise LoadError, "require_relative is called in #{$1}" end absolute = File.expand_path(relative_feature, File.dirname(file)) require absolute end end # DEPRECATED # alias_method :require_local, :require_relative unless private_method_defined?(:load_relative) # 1.9 # Load file from same dir as calling script... # # load_local 'myscript' # # CREDIT: Paul Brannan, Pragmatic Programmers # def load_relative(relative_feature, safe=nil) c = caller.first fail "Can't parse #{c}" unless c.rindex(/:\d+(:in `.*')?$/) file = $` # File.dirname(c) if /\A\((.*)\)/ =~ file # eval, etc. raise LoadError, "require_relative is called in #{$1}" end absolute = File.expand_path(relative_feature, File.dirname(file)) load absolute, safe end end # DEPRECATED # alias_method :load_local, :load_relative end facets-2.9.3/lib/core/facets/kernel/respond.rb0000644000004100000410000000161311714455226021254 0ustar www-datawww-datarequire 'facets/functor' module Kernel # Like #respond_to? but returns the result of the call # if it does indeed respond. # # class RespondExample # def f; "f"; end # end # # x = RespondExample.new # x.respond(:f) #=> "f" # x.respond(:g) #=> nil # # or # # x.respond.f #=> "f" # x.respond.g #=> nil # # This method was known as #try until Rails defined #try # to be something more akin to #ergo. # # CREDIT: Trans, Chris Wanstrath def respond(sym=nil, *args, &blk) if sym return nil if not respond_to?(sym) __send__(sym, *args, &blk) else ## TODO: use after 1.8.6 not supported anymore ##Functor.new do |op, *a, &b| ## respond(op, *a, &b) ##end Functor.new(&method(:respond).to_proc) end end # DEPRECATED: #respond is enough. #alias_method :respond_with_value, :respond end facets-2.9.3/lib/core/facets/kernel/__callee__.rb0000644000004100000410000000004311714455226021617 0ustar www-datawww-datarequire 'facets/kernel/__method__' facets-2.9.3/lib/core/facets/kernel/d.rb0000644000004100000410000000064311714455226020027 0ustar www-datawww-datamodule Kernel # Like #p but gives file and line number... # # d("hi") # # produces ... # # "hi" (/home/dave/projects/foo.rb, 38) # def d(*x) puts "#{x.inspect} #{caller[0]}" return *x end #-- # Old definition ... # # def d(*x) # puts "#{__FILE__}, #{__LINE__}" # x.each{ |e| puts e.inspect } #p(*x) # x.size > 1 ? x : x.last #x.last # end #++ end facets-2.9.3/lib/core/facets/kernel/presence.rb0000644000004100000410000000003611714455226021404 0ustar www-datawww-datarequire 'facets/kernel/blank' facets-2.9.3/lib/core/facets/kernel/source_location.rb0000644000004100000410000000027311714455226022773 0ustar www-datawww-datamodule Kernel unless method_defined?(:source_location) # 1.9 def source_location file, line, meth = *caller(1).first.split(':') return file, line end end end facets-2.9.3/lib/core/facets/kernel/ergo.rb0000644000004100000410000000135411714455226020540 0ustar www-datawww-datarequire 'facets/functor' module Kernel # Yield self -or- return self. # # "a".ergo.upcase #=> "A" # nil.ergo.foobar #=> nil # # "a".ergo{ |o| o.upcase } #=> "A" # nil.ergo{ |o| o.foobar } #=> nil # # This is like #tap, but #tap yields self and returns self, # where as #ergo yields self buit return the result. # # CREDIT: Daniel DeLorme def ergo(&b) if block_given? b.arity == 1 ? yield(self) : instance_eval(&b) else self end end end class NilClass # Compliments Kernel#ergo. # # "a".ergo{ |o| o.upcase } #=> "A" # nil.ergo{ |o| o.bar } #=> nil # # CREDIT: Daniel DeLorme def ergo @_ergo ||= Functor.new{ nil } @_ergo unless block_given? end end facets-2.9.3/lib/core/facets/kernel/writers.rb0000644000004100000410000000455711714455226021313 0ustar www-datawww-datamodule Kernel # Returns an Array of methods ending in '='. # # class WritersExample # attr_reader :a, :b # attr_accessor :x, :y # private # def q=(q); @q=q; end # end # # w = WritersExample.new # # syms = w.writers # [:x=, :y=] # # syms.include?(:x=) #=> true # syms.include?(:y=) #=> true # # If the +chomp+ option is true, then the trailing '=' will be removed. # # syms = w.writers(:chomp=>true) # # syms.include?(:x) #=> true # syms.include?(:y) #=> true # # By default #writers only includes public methods. To see private or # protected methods use the +:access+ option. # # w.writers(:access=>:private) #=> [:q=] # # Or multiple access options, # # syms = w.writers(:access=>[:public,:private]) # [:q=,:x=,:y=] # # syms.include?(:q=) #=> true # syms.include?(:x=) #=> true # syms.include?(:y=) #=> true # # You can simply supply `:all` to get all method regardless accessibility. # # Also, by default this method excludes all writers defined in Object # or Kernel. To include these set +ancestors+ to Object or Kernel. # # w.writers(Object) # # TODO: Create Module#instance_writers. def writers(*ancestors_and_options) options = (Hash === ancestors_and_options.last ? ancestors_and_options.pop : {}) chomp = options[:chomp] access = options[:access] || [] ancestors = ancestors_and_options.first access = [access].flatten if access.include?(:all) access.concat([:public, :protected, :private]) end access << :public if access.empty? writers = [] if access.include?(:private) writers += private_methods(ancestors).select{ |m| /=$/ =~ m.to_s } end if access.include?(:protected) writers += protected_methods(ancestors).select{ |m| /=$/ =~ m.to_s } end if access.include?(:public) writers += public_methods(ancestors).select{ |m| /=$/ =~ m.to_s } end if ancestors == Kernel exclude = nil elsif ancestors == Object exclude = Kernel else exclude = Object end if exclude kernel_writers = exclude.instance_methods.select{ |m| /=$/ =~ m.to_s } writers = writers - kernel_writers end writers = writers.map{ |w| w.to_s.chomp('=') } if chomp writers.map{ |w| w.to_sym } end end facets-2.9.3/lib/core/facets/kernel/case.rb0000644000004100000410000000016511714455226020516 0ustar www-datawww-datamodule Kernel def case?(*matchers) matchers.all?{ |m| m === self } end unless method_defined?(:case?) end facets-2.9.3/lib/core/facets/kernel/object_send.rb0000644000004100000410000000111511714455226022056 0ustar www-datawww-datamodule Kernel # Send only to public methods. # # class SendExample # private # def foo; end # end # # obj = SendExample.new # # expect NoMethodError do # obj.object_send(:foo) # end # # TODO: object_send needs to change for 1.9. Is it #public_send ? # # CREDIT: Trans #-- # Which implementation is faster? #++ def object_send(name, *args, &blk) #instance_eval "self.#{name}(*args)" if respond_to?(name) __send__(name, *args, &blk) else __send__(:method_missing, name, *args, &blk) end end end facets-2.9.3/lib/core/facets/kernel/equate.rb0000644000004100000410000000063511714455226021071 0ustar www-datawww-datamodule Kernel # Broad equality. Checks to see if the object +x+ is in any # way equal to the reciever, starting with the identity # #equal?, then #eql?, then #==, and ending with #===. # # 1.equate?(1.0) #=> true # "string".equate?("string") #=> true # String.equate?("string") #=> true # def equate?(x) equal?(x) || eql?(x) || self == x || self === x end end facets-2.9.3/lib/core/facets/kernel/no.rb0000644000004100000410000000003411714455226020212 0ustar www-datawww-datarequire 'facets/kernel/yes' facets-2.9.3/lib/core/facets/kernel/instance_exec.rb0000644000004100000410000000246211714455226022415 0ustar www-datawww-dataclass Object #module Kernel unless method_defined?(:instance_exec) # 1.9 require 'thread' module InstanceExecMethods #:nodoc: end include InstanceExecMethods # Evaluate the block with the given arguments within the context of # this object, so self is set to the method receiver. # # From Mauricio's http://eigenclass.org/hiki/bounded+space+instance_exec # # This version has been borrowed from Rails for compatibility sake. # # NOTE: This is not a common core extension (due to the use of thread.rb) # and is not loaded automatically when using require 'facets'. # However it is a core method in Ruby 1.9, so this only matters for users # of Ruby 1.8.x or below. # # @uncommon # require 'facets/kernel/instance_exec' # def instance_exec(*args, &block) begin old_critical, Thread.critical = Thread.critical, true n = 0 n += 1 while respond_to?(method_name = "__instance_exec#{n}") InstanceExecMethods.module_eval { define_method(method_name, &block) } ensure Thread.critical = old_critical end begin __send__(method_name, *args) ensure InstanceExecMethods.module_eval { remove_method(method_name) } rescue nil end end end end facets-2.9.3/lib/core/facets/kernel/deep_copy.rb0000644000004100000410000000166311714455226021556 0ustar www-datawww-datamodule Kernel # Anything that can be marshaled can be copied in totality. # # "ABC".deep_copy #=> "ABC" # # NOTE: Not sure why we wouldn't just call this #copy, but # the term +deep_copy+ seems to be the common practive. def deep_copy Marshal::load(Marshal::dump(self)) end # def deep_clone(cache={}) return cache[self] if cache.key?(self) #@deep_cloning_obj if @deep_cloning copy = clone cache[self] = copy #@deep_cloning_obj = clone copy.instance_variables.each do |var| val = instance_variable_get(var) begin #@deep_cloning = true val = val.deep_clone(cache) rescue TypeError next ensure #@deep_cloning = false end copy.instance_variable_set(var, val) #@deep_cloning_obj.instance_variable_set(var, val) end #deep_cloning_obj = @deep_cloning_obj #@deep_cloning_obj = nil #deep_cloning_obj copy end end facets-2.9.3/lib/core/facets/kernel/try.rb0000644000004100000410000000207611714455226020424 0ustar www-datawww-datarequire 'facets/functor' module Kernel # Invokes the method identified by the symbol +method+, passing it any # arguments and/or the block specified, just like the regular Ruby # Object#send does. # # *Unlike* that method however, a +NoMethodError+ exception will *not* # be raised and +nil+ will be returned instead, if the receiving object # is a +nil+ object or NilClass. # # For example, without try # # @example = Struct.new(:name).new("bob") # # @example && @example.name # # or: # # @example ? @example.name : nil # # But with try # # @example.try(:name) #=> "bob" # # or # # @example.try.name #=> "bob" # # It also accepts arguments and a block, for the method it is trying: # # @people.try(:collect){ |p| p.name } # def try(method=nil, *args, &block) if method __send__(method, *args, &block) else self end end end class NilClass # See Kernel#try. def try(method=nil, *args) if method nil else Functor.new{ nil } end end end facets-2.9.3/lib/core/facets/kernel/yes.rb0000644000004100000410000000056311714455226020405 0ustar www-datawww-datarequire 'facets/kernel/ask' module Kernel # Ask a question expecting a yes answer. def yes?(question) case ask(question).downcase when 'y', 'yes' true else false end end # Ask a question expecting a no answer. def no?(question) case ask(question).downcase when 'n', 'no' true else false end end end facets-2.9.3/lib/core/facets/kernel/not.rb0000644000004100000410000000100211714455226020372 0ustar www-datawww-datarequire 'facets/functor' module Kernel # Same as using NOT operator '!'. # # true.nil?.not? == !true.nil? # def not? !self end # Inversion functor. # # true.not.nil? #=> true # def not Functor.new(&method(:not_send).to_proc) end ## TODO: When we no longer need to support 1.8.6 we can use: ## ## def not ## Functor.new do |op, *a, &b| ## !__send__(op, *a, &b) ## end ## end private # def not_send(op, *a, &b) !__send__(op, *a) end end facets-2.9.3/lib/core/facets/kernel/__method__.rb0000644000004100000410000000175511714455226021665 0ustar www-datawww-datamodule Kernel unless defined?(__method__) == "method" # 1.8.7+ # Retreive the current running method name. # # def method_example # __method__ # end # # method_example #=> :method_example # # Technically __callee__ should provided alias names, # where __method__ should not. But we'll have to # leave that distinction to Ruby 1.9+. def __method__ /\`([^\']+)\'/.match(caller(1).first)[1].to_sym end private :__method__ end unless defined?(__callee__) == "method" # 1.9+ # Retreive the current running method name. # # def callee_example # __callee__ # end # # callee_example #=> :callee_example # # Technically __callee__ should provided alias names, # where as __method__ should not. But we'll have to # leave that distinction to Ruby 1.9+. def __callee__ /\`([^\']+)\'/.match(caller(1).first)[1].to_sym end private :__callee__ end end facets-2.9.3/lib/core/facets/kernel/qua_class.rb0000644000004100000410000000115511714455226021556 0ustar www-datawww-datamodule Kernel # Easy access to an object qua class, otherwise known as the object's # singleton class. #qua_class can also take a block. # # string = "Hello World" # # string.qua_class do # def important # self + "!" # end # end # # string.important #=> "Hello World!" # # Yes, another one. # # CREDIT: Trans def qua_class(&block) if block_given? (class << self; self; end).class_eval(&block) else (class << self; self; end) end end # The +qua_class+ method can also be written +quaclass+. alias_method :quaclass, :qua_class end facets-2.9.3/lib/core/facets/kernel/meta_eval.rb0000644000004100000410000000054611714455226021543 0ustar www-datawww-datarequire 'facets/kernel/meta_class' module Kernel # Evaluate code in a metaclass. This is equivalent to: # # meta_class.instance_eval(...) # # CREDIT: WhyTheLuckyStiff def meta_eval(str=nil, *file_and_line, &blk) if str meta_class.instance_eval(str, *file_and_line) else meta_class.instance_eval(&blk) end end end facets-2.9.3/lib/core/facets/kernel/val.rb0000644000004100000410000000061011714455226020360 0ustar www-datawww-datamodule Kernel # Tests to see if something has value. An object # is considered to have value if it is not nil? # and if it responds to #empty?, is not empty. # # nil.val? #=> false # [].val? #=> false # 10.val? #=> true # [nil].val? #=> true def val? return false if nil? return false if empty? if respond_to?(:empty?) true end end facets-2.9.3/lib/core/facets/kernel/object_hexid.rb0000644000004100000410000000122511714455226022230 0ustar www-datawww-datamodule Kernel ARCH_SIZE = (['a'].pack('P').length > 4 ? 64 : 32) if RUBY_VERSION < '1.9' if ARCH_SIZE == 64 HEXID_TEMPLATE = "0x%012x" else HEXID_TEMPLATE = "0x%x" end else if ARCH_SIZE == 64 HEXID_TEMPLATE = "0x%014x" else HEXID_TEMPLATE = "0x%x" end end # Returns the object id as a string in hexideciaml, # which is how Ruby reports them with inspect... # # "ABC".object_hexid #=> "0x402d359c" # def object_hexid HEXID_TEMPLATE % (__id__ << 1) end # The 1.9.3 definition is as follows: #def object_hexid # "0x" + [object_id << 1].pack("L>!").unpack("H*")[0] #end end facets-2.9.3/lib/core/facets/kernel/__dir__.rb0000644000004100000410000000105011714455226021147 0ustar www-datawww-datamodule Kernel # Similar to __FILE__, __DIR__ provides the directory # path to the current executing script. # # CREDIT: Trans def __DIR__(*paths) c = caller.first return nil unless c.rindex(/:\d+(:in `.*')?$/) file = $` # File.dirname(c) return nil if /\A\((.*)\)/ =~ file # eval, etc. #File.expand_path(File.join(File.dirname(file), paths)) File.join(File.dirname(file), paths) end #-- # Old defintion ... # # def __DIR__ # (/^(.+)?:\d+/ =~ caller[0]) ? File.dirname($1) : nil # end #++ end facets-2.9.3/lib/core/facets/kernel/deep_clone.rb0000644000004100000410000000004211714455226021672 0ustar www-datawww-datarequire 'facets/kernel/deep_copy' facets-2.9.3/lib/core/facets/kernel/__set__.rb0000644000004100000410000000004011714455226021162 0ustar www-datawww-datarequire 'facets/kernel/__get__' facets-2.9.3/lib/core/facets/kernel/meta_alias.rb0000644000004100000410000000057711714455226021711 0ustar www-datawww-datarequire 'facets/kernel/meta_class' module Kernel # Alias a method defined in the metaclass (ie. singleton class). # # class MetaExample # def self.y?; "y?" ; end # end # # MetaExample.meta_alias "ynot?", "y?" # # MetaExample.ynot? #=> "y?" # # CREDIT: Trans def meta_alias(*args) meta_class do alias_method(*args) end end end facets-2.9.3/lib/core/facets/kernel/__class__.rb0000644000004100000410000000034611714455226021505 0ustar www-datawww-datamodule Kernel # Defines core method __class__ as an alias of class. # This allows you to use #class as your own method, without # loosing the ability to determine the object's class. alias_method :__class__, :class end facets-2.9.3/lib/core/facets/kernel/p.rb0000644000004100000410000000061211714455226020037 0ustar www-datawww-datamodule Kernel # Alternate to standard #p method that outputs # Kernel#inspect to stdout, but also passes through # the orginal argument(s) ... # # x = 1 # r = 4 + p(1) # p r # # produces ... # # 1 # 5 # # TODO: DEPRECATE as of 1.9, _if_ it will do this. def p(*x) x.each{ |e| puts e.inspect } #p(*x) x.size > 1 ? x : x.last #x.last end end facets-2.9.3/lib/core/facets/kernel/assign_from.rb0000644000004100000410000000003711714455226022110 0ustar www-datawww-datarequire 'facets/kernel/assign' facets-2.9.3/lib/core/facets/kernel/false.rb0000644000004100000410000000003611714455226020672 0ustar www-datawww-datarequire 'facets/kernel/true' facets-2.9.3/lib/core/facets/kernel/super_method.rb0000644000004100000410000000043211714455226022276 0ustar www-datawww-datamodule Kernel # Returns method of a parent class bound to self. def super_method(klass, meth) unless self.class.ancestors.include?(klass) raise ArgumentError, "Not an ancestor for super_method-- #{klass}" end klass.instance_method(meth).bind(self) end end facets-2.9.3/lib/core/facets/kernel/trap_chain.rb0000644000004100000410000000204211714455226021707 0ustar www-datawww-datamodule Kernel # Calling Kernel#trap() by itself will replace any previously registered # handler code. Kernel#trap_chain(), on the other hand, will add the block # you supply to the existing "list" of registered handler blocks. Similar # to the way Kernel#at_exit() works, Kernel#trap_chain() will prepend the # given block to the call chain for the given signal_name. When the signal # occurs, your block will be executed first and then the previously # registered handler will be invoked. This can be called repeatedly # to create a "chain" of handlers. # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # CREDIT: Tyler Rick # # @uncommon # require 'facets/kernel/trap_chain' # def trap_chain(signal_name, *args, &block) previous_interrupt_handler = trap(signal_name, *args) {} trap(signal_name, *args) do block.call previous_interrupt_handler.call unless previous_interrupt_handler == "DEFAULT" end end end facets-2.9.3/lib/core/facets/kernel/memo.rb0000644000004100000410000000137311714455226020542 0ustar www-datawww-datarequire 'facets/binding/eval' require 'facets/kernel/__method__' module Kernel # Global memo cache. $MEMO ||= {} # Memoize a method. # # class MemoExample # attr_accessor :a # def m # memo{ @a } # end # end # # ex = MemoExample.new # # ex.a = 10 # ex.m #=> 10 # # ex.a = 20 # ex.m #=> 10 # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # @uncommon # require 'facets/kernel/memo' # def memo(*args, &block) if args.empty? args = block.binding.eval('[self, __method__]') end if $MEMO.key?(args) $MEMO[args] else $MEMO[args] = block.call end end end facets-2.9.3/lib/core/facets/kernel/require_all.rb0000644000004100000410000000247111714455226022111 0ustar www-datawww-datamodule Kernel # Require a pattern of files relatvie to the current file. # This makes is easy to require an entire directory, for instance: # # require_all 'core_ext/*' # # NOTE: This method used to allow glob-based requires from the $LOAD_PATH, # but this was deprecated in favor of relative requiring only, as it is # consider the typical usecase, and globbing from the $LOAD_PATH is a # bit dangerous. Better options exist for globbing the $LOAD_PATH such as # the +plugins+ gem. def require_all(pattern) c = caller.first fail "Can't parse #{c}" unless c.rindex(/:\d+(:in `.*')?$/) file = $` # File.dirname(c) if /\A\((.*)\)/ =~ file # eval, etc. raise LoadError, "require_relative is called in #{$1}" end glob = File.expand_path(pattern, File.dirname(file)) Dir.glob(glob).each do |absolute| require absolute end end # Same as #require_all, but for #load. def load_all(pattern, safe=nil) c = caller.first fail "Can't parse #{c}" unless c.rindex(/:\d+(:in `.*')?$/) file = $` # File.dirname(c) if /\A\((.*)\)/ =~ file # eval, etc. raise LoadError, "require_relative is called in #{$1}" end glob = File.expand_path(pattern, File.dirname(file)) Dir.glob(glob).each do |absolute| load absolute, safe end end end facets-2.9.3/lib/core/facets/kernel/hierarchical_send.rb0000644000004100000410000000250211714455226023227 0ustar www-datawww-datarequire 'facets/class/hierarchically' module Kernel # Send a message to each ancestor in an object's class hierarchy. # The method will only be called if the method is defined for the # ancestor. # # This can be very useful for setting up a `preinitialize` system. # # m = Module.new do # attr :a # def preinitialize # @a = 1 # end # end # # c = Class.new do # include m # def initialize # hierarchical_send(:preinitialize) # end # end # # c.new.a #=> 1 # # @todo Include singleton class? def hierarchical_send(method_name, *args, &block) method_name = method_name.to_s if RUBY_VERSION < '1.9' this = self self.class.hierarchically do |anc| ## is there really no better way to check for the method? if anc.instance_methods(false).include?(method_name) or anc.public_instance_methods(false).include?(method_name) or anc.private_instance_methods(false).include?(method_name) or anc.protected_instance_methods(false).include?(method_name) im = anc.instance_method(method_name) ##im.arity == 0 ? im.bind(this).call(&block) : im.bind(this).call(*args, &block) im.bind(this).call(*args, &block) end end end end facets-2.9.3/lib/core/facets/kernel/singleton_class.rb0000644000004100000410000000033411714455226022770 0ustar www-datawww-datamodule Kernel # Easy access to an object's "special" class. # # NOTE: This is already defined in Ruby 1.9+. def singleton_class (class << self; self; end) end unless method_defined?(:singleton_class) end facets-2.9.3/lib/core/facets/kernel/ask.rb0000644000004100000410000000077411714455226020367 0ustar www-datawww-datamodule Kernel module_function # Very simple convenience method to get user input # via the console. A prompt will be sent to $stdout, # if given, and the input taken from $stdin... # # ask "Are you happy? [Yn]" # # On the command line one would see... # # Are you happy? [Yn] # # Responding... # # Are you happy? [Yn] Y # # The ask method would return "Y". def ask(prompt=nil) $stdout << "#{prompt}" $stdout.flush $stdin.gets.chomp! end end facets-2.9.3/lib/core/facets/kernel/method.rb0000644000004100000410000000327211714455226021065 0ustar www-datawww-data$FIRST_CLASS_METHODS = Hash.new{ |h,k| h[k] = {} } module Kernel # Easy access to method as object, and they retain state. # # def hello # puts "Hello World!" # end # # m1 = method!(:hello) # # def m1.annotate # "simple example" # end # # m2 = method!(:hello) # m2.annotate #=> "simple example" # def method!(s) #( @__methods__ ||= {} )[s.to_sym] ||= method(s) $FIRST_CLASS_METHODS[self][s.to_sym] ||= method(s) end end #-- # Should 1st Class Methods be part of Ruby proper? # # Perhaps the best solution would be using the notation # ::ameth. This would require some minor changes # to Ruby, but with few backward incompatabilites if # parantheticals revert back to the actual method invocation. # Although this later stipulation means capitalized methods # would not be accessible in this way b/c they would intefere with # constant lookup. It's a trade off. ... # # Current Proposed Alternate # ----------------- ------------------ ------------------- # Foo.Bar() method call method call method call # Foo.Bar method call method call method call # Foo.bar() method call method call method call # Foo.bar method call method call method call # Foo::Bar() method call method call 1st class method # Foo::Bar constant lookup constant lookup constant lookup # Foo::bar() method call method call 1st class method # Foo::bar method call 1st class method 1st class method # # Then again this dosen't address bound versus unbound. #++ facets-2.9.3/lib/core/facets/kernel/meta_def.rb0000644000004100000410000000047411714455226021352 0ustar www-datawww-datarequire 'facets/kernel/meta_class' module Kernel # Add method to a meta-class --i.e. a singleton method. # # class X; end # X.meta_def(:x){"x"} # X.x #=> "x" # # CREDIT: WhyTheLuckyStiff def meta_def( name, &block ) meta_class do define_method( name, &block ) end end end facets-2.9.3/lib/core/facets/kernel/instance_class.rb0000644000004100000410000000141211714455226022570 0ustar www-datawww-datamodule Kernel # Kernel extension prefixed by instance_ which provide # internal (eg private) access to the object. # Kernel extension using instance_ prefix which is beneficial # to separation of metaprogramming from general programming. # object_ methods, in contrast to the instance_ methods, # do not access internal state. # Easy access to an object qua class, otherwise known # as the object's metaclass or singleton class. This # implemnetation alwasy returns the class, even if a # block is provided to eval against it... # # It is what it is. # But I think I like this one best. # # CREDIT: Trans def instance_class(&block) (class << self; self; end).module_eval(&block) if block (class << self; self; end) end end facets-2.9.3/lib/core/facets/kernel/with.rb0000644000004100000410000000046111714455226020555 0ustar www-datawww-datamodule Kernel # Like returning but exectues the block # via instance_eval. # # def foo # with values = [] do # self << 'bar' # self << 'baz' # end # end # # foo # => ['bar', 'baz'] # def with(obj=self, &block) obj.instance_eval(&block) end end facets-2.9.3/lib/core/facets/kernel/complete.rb0000644000004100000410000000057311714455226021416 0ustar www-datawww-datamodule Kernel # Repeat loop until it yeilds false or nil. # # a = [3, 2, 1] # b = [] # # complete do # x = a.pop # b << x # x # end # # b #=> [1, 2, 3, nil] # # Be "aware" when using this method, it easy to accidently # induce infinite loops. # # CREDIT: Trans def complete loop { break unless yield } end end facets-2.9.3/lib/core/facets/kernel/here.rb0000644000004100000410000000021411714455226020521 0ustar www-datawww-datamodule Kernel # A shorthand pronoun for binding(). # # a = 3 # eval("a", here) #=> 3 # alias_method :here, :binding end facets-2.9.3/lib/core/facets/kernel/temporarily.rb0000644000004100000410000000100711714455226022146 0ustar www-datawww-datamodule Kernel # Temporarily set variables while yielding a block, then return the # variables to their original settings when complete. # # temporarily('$VERBOSE'=>false) do # $VERBOSE.assert == false # end # def temporarily(settings) #:yield: cache = {} settings.each do |var, val| cache[var] = eval("#{var}") eval("proc{ |v| #{var} = v }").call(val) end yield ensure cache.each do |var, val| eval("proc{ |v| #{var} = v }").call(val) end end end facets-2.9.3/lib/core/facets/kernel/true.rb0000644000004100000410000000066011714455226020562 0ustar www-datawww-datamodule Kernel # Returns true is an object is class TrueClass, # otherwise false. # # true.true? #=> true # false.true? #=> false # nil.true? #=> false # def true? (true == self) end # Returns true is an object is class FalseClass, # otherwise false. # # true.false? #=> false # false.false? #=> true # nil.false? #=> false # def false? (false == self) end end facets-2.9.3/lib/core/facets/kernel/extension.rb0000644000004100000410000000023511714455226021615 0ustar www-datawww-datamodule Kernel # TODO: Must reduce the number of singleton method methods. # Don't say it! # def extension class << self; self; end end end facets-2.9.3/lib/core/facets/kernel/instance_assign.rb0000644000004100000410000000054311714455226022753 0ustar www-datawww-datamodule Kernel # Set instance variables using a hash. # # instance_assign('@a'=>1, '@b'=>2) # @a #=> 1 # @b #=> 2 # # DEPRECATE: Use instance.update instead of #instance_assign. def instance_assign(hash) hash.each do |k,v| k = "@#{k}" if k !~ /^@/ instance_variable_set(k, v) end return self end end facets-2.9.3/lib/core/facets/kernel/eigen.rb0000644000004100000410000000144611714455226020675 0ustar www-datawww-datarequire 'facets/functor' module Kernel # Call methods on the eigenclass (i.e. the singleton_class). # # name = "Tom" # name.eigen.define_method(:turkey){ self + " Turkey" } # name.turkey #=> "Tom Turkey" # # One the nice things you can do with #eigen, is define class attributes # without having to open a `class << self` block. # # c = Class.new do # eigen.attr_accessor :a # end # c.a = 1 # c.a #=> 1 # # NOTE: This was once called `#meta`, but meta is such a generic # and overly used term that 'eigen' was decided upon as a better # choice. You can thank or blame _why for the term, if you like. # def eigen Functor.new do |op,*a,&b| (class << self; self; end).class_eval do __send__(op,*a,&b) end end end end facets-2.9.3/lib/core/facets/kernel/assign.rb0000644000004100000410000000326411714455226021072 0ustar www-datawww-datarequire 'facets/na' module Kernel # Assign via writer using arguments, hash or associative array. # # Using name-value arguments: # # object = Object.new # # object.assign(:a, 1) # object.assign(:b, 2) # # Using a hash: # # object.assign(:a => 1, :b => 2) # # Use an associative array: # # object.assign([[:a, 1], [:b, 2]]) # # These are all equivalent to: # # object.a = 1 if object.respond_to?(:a=) # object.b = 2 if object.respond_to?(:b=) # # Using an associative array instead of a hash guarantees order of assignment # for older versions of Ruby (< 1.8.7). # # TODO: Should this be called #set instead? Consider Module#set in this # question, and also #set_from as the alias of #assign_from. def assign(data=nil, value=NA) return self unless data if value==NA data.each do |(k,v)| __send__("#{k}=", v) if respond_to?("#{k}=") end else __send__("#{data}=", value) if respond_to?("#{data}=") end self end # Set attribute writers using like readers from another object. # # class AssignExample # attr_accessor :a, :b # def initialize(a, b) # @a, @b = a, b # end # end # # obj1 = AssignExample.new(1,2) # obj2 = AssignExample.new(3,4) # # obj2.assign_from(obj1, :a, :b) # # obj2.a #=> 1 # obj2.b #=> 2 # # TODO: Should this be called #set_from ? def assign_from(obj, *fields) fields.flatten.each do |k| send("#{k}=", obj.__send__("#{k}")) #if self.respond_to?("#{k}=") && obj.respond_to?("#{k}") end end ## DEPRECATED: Original name for #assign_from. ##alias_method :set_from, :assign_from end facets-2.9.3/lib/core/facets/kernel/not_nil.rb0000644000004100000410000000041211714455226021240 0ustar www-datawww-datamodule Kernel # The opposite of #nil?. # # "hello".not_nil? # -> true # nil.not_nil? # -> false # # CREDIT: Gavin Sinclair def not_nil? ! nil? end # DEPRECATED: #not_nil? it enough. #alias_method :non_nil?, :not_nil? end facets-2.9.3/lib/core/facets/kernel/as.rb0000644000004100000410000000550611714455226020212 0ustar www-datawww-datarequire 'facets/functor' module Kernel # Returns a As-functor that allows one to call any # ancestor's method directly of the given object. # # class AsExample1 # def x ; 1 ; end # end # # class AsExample2 < AsExample1 # def x ; 2 ; end # end # # class AsExample3 < AsExample2 # def x ; as(AsExample1).x ; end # end # # AsExample1.new.x #=> 1 # def as(ancestor, &blk) ##this = self r = As.new(self, ancestor) ##unless r ## r = As.cache[self][ancestor] = Functor.new do |op, *a, &b| ## ancestor.instance_method(op).bind(this).call(*a,&b) ## end ##end r.instance_eval(&blk) if block_given? #yield(r) if block_given? r end # Call parent class/module methods once bound to self. # # TODO: Does this have the proper scope for #send? def send_as(ancestor, sym, *args, &blk) ancestor.instance_method(sym).bind(self).call(*args,&blk) end #-- # Old version ... # # def send_as(klass, meth, *args, &blk) # selfclass = Kernel.instance_method(:class).bind(self).call # raise ArgumentError if ! selfclass.ancestors.include?(klass) # klass.instance_method(meth).bind(self).call(*args, &blk) # end #++ ## DEPRECATED: There's no reliable way to get method name of caller. ## This needs to have the same knowledge that #super itself has and ## I do not thin that is possbile in pure Ruby. ## ## Like super but skips to a specific ancestor module or class. ## ## class SuperAsExample1 ## def x ; 1 ; end ## end ## ## class SuperAsExample2 < SuperAsExample1 ## def x ; 2 ; end ## end ## ## class SuperAsExample3 < SuperAsExample2 ## def x ; super_as(SuperAsExample1) ; end ## end ## ## SuperAsExample3.new.x #=> 1 ## ##def super_as(klass=self.class.superclass, *args, &blk) ## unless self.class.ancestors.include?(klass) ## raise ArgumentError ## end ## #called = /\`([^\']+)\'/.match(caller(1).first)[1].to_sym ## called = File.basename(caller(1).first) ## klass.instance_method(called).bind(self).call(*args,&blk) ##end end # Support class for Kernel#as. # # TODO: Deprecate this and use Functor (HigherOrderMessage) instead ? class As #:nodoc: class << self alias_method :_new, :new def new(subject, ancestor) cache[subject][ancestor] ||= _new(subject, ancestor) end def cache @cache ||= Hash.new{|h,k| h[k]={} } end private :_new private :cache end # Privatize all methods except #binding an operators. private(*instance_methods.select { |m| m !~ /(^__|^\W|^binding$)/ }) def initialize(subject, ancestor) @subject = subject @ancestor = ancestor end private def method_missing(sym, *args, &blk) @ancestor.instance_method(sym).bind(@subject).call(*args,&blk) end end facets-2.9.3/lib/core/facets/kernel/callstack.rb0000644000004100000410000000004311714455226021537 0ustar www-datawww-datarequire 'facets/kernel/call_stack' facets-2.9.3/lib/core/facets/object/0000755000004100000410000000000011714455226017242 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/object/dup.rb0000644000004100000410000000316511714455226020364 0ustar www-datawww-dataclass Object # Override this in a child class if it cannot be dup'ed. # # obj1 = Object.new # obj2 = obj1.dup! # obj2.equal?(obj1) #=> false # # CREDIT: Dan Kubb (extlib) def dup! dup end # Alternative name for #dup! def try_dup dup! end # Can you safely call #dup on this object? # # Returns +false+ for +nil+, +false+, +true+, symbols, and numbers; # +true+ otherwise. def dup? ; true ; end def clone? ; true ; end end class NilClass # Since NilClass is immutable it cannot be duplicated. # For this reason #try_dup returns +self+. # # nil.dup! #=> nil # def dup! ; self ; end def dup? ; false ; end def clone? ; false ; end end class FalseClass # Since FalseClass is immutable it cannot be duplicated. # For this reason #try_dup returns +self+. # # false.dup! #=> false # def dup! ; self ; end def dup? ; false ; end def clone? ; false ; end end class TrueClass # Since TrueClass is immutable it cannot be duplicated. # For this reason #try_dup returns +self+. # # true.dup! #=> true # def dup! ; self ; end def dup? ; false ; end def clone? ; false ; end end class Symbol # Since Symbol is immutable it cannot be duplicated. # For this reason #try_dup returns +self+. # # :a.dup! #=> :a # def dup! ; self ; end def dup? ; false ; end def clone? ; false ; end end class Numeric # Since Numeric is immutable it cannot be duplicated. # For this reason #try_dup returns +self+. # # 1.dup! #=> 1 # def dup! ; self ; end def dup? ; false ; end def clone? ; false ; end end facets-2.9.3/lib/core/facets/object/clone.rb0000644000004100000410000000003411714455226020664 0ustar www-datawww-datarequire 'facets/object/dup' facets-2.9.3/lib/core/facets/object/object_state.rb0000644000004100000410000000303111714455226022232 0ustar www-datawww-dataclass Object # Get or set state of object. You can think of #object_state as an in-code # form of marshalling. # # class StateExample # attr_reader :a, :b # def initialize(a,b) # @a, @b = a, b # end # end # # obj = StateExample.new(1,2) # obj.a #=> 1 # obj.b #=> 2 # # obj.object_state #=> {:a=>1, :b=>2} # # obj.object_state(:a=>3, :b=>4) # obj.a #=> 3 # obj.b #=> 4 # # For most object's this is essentially the same as instance.to_h. # But for data structures like Array and Hash it returns a snapshot of their # contents, not the state of their instance variables. #-- # TODO: Should this be in module Kernel ? #++ def object_state(data=nil) if data instance_variables.each do |iv| name = iv.to_s.sub(/^[@]/, '').to_sym instance_variable_set(iv, data[name]) end else data = {} instance_variables.each do |iv| name = iv.to_s.sub(/^[@]/, '').to_sym data[name] = instance_variable_get(iv) end data end end end class Array # def object_state(data=nil) data ? replace(data) : dup end end class String # def object_state(data=nil) data ? replace(data) : dup end end class Hash # def object_state(data=nil) data ? replace(data) : dup end end class Struct # def object_state(data=nil) if data data.each_pair {|k,v| send(k.to_s + "=", v)} else data = {} each_pair{|k,v| data[k] = v} data end end end facets-2.9.3/lib/core/facets/object/replace.rb0000644000004100000410000000200411714455226021176 0ustar www-datawww-dataclass Object # Replace state of object with the state of another object of the # same class (or superclass). # # class ReplaceExample # attr_reader :a, :b # def initialize(a,b) # @a, @b = a, b # end # end # # obj1 = ReplaceExample.new(1,2) # obj1.a #=> 1 # obj1.b #=> 2 # # obj2 = ReplaceExample.new(3,4) # obj2.a #=> 3 # obj2.b #=> 4 # # obj1.replace(obj2) # obj1.a #=> 3 # obj1.b #=> 4 # # This is very similar to instance.update, but it is limited # by the class of objects, in the same manner as Array#replace. def replace(source) raise ArgumentError, "not a #{self.class} -- #{source}" unless source.is_a?(self.class) instance_variables.each do |iv| instance_variable_set(iv, source.instance_variable_get(iv)) end end end class Struct # Struct#replace can take any +source+ that responds to #each_pair. def replace(source) source.each_pair{ |k,v| send(k.to_s + "=", v) } end end facets-2.9.3/lib/core/facets/object/try_dup.rb0000644000004100000410000000003411714455226021252 0ustar www-datawww-datarequire 'facets/object/dup' facets-2.9.3/lib/core/facets/object.rb0000644000004100000410000000034311714455226017567 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'object/clone.rb' require_relative 'object/dup.rb' require_relative 'object/object_state.rb' require_relative 'object/replace.rb' require_relative 'object/try_dup.rb' facets-2.9.3/lib/core/facets/symbol.rb0000644000004100000410000000077211714455226017634 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'symbol/as_s.rb' require_relative 'symbol/bang.rb' require_relative 'symbol/chomp.rb' require_relative 'symbol/generate.rb' require_relative 'symbol/not.rb' require_relative 'symbol/op_div.rb' require_relative 'symbol/plain.rb' require_relative 'symbol/query.rb' require_relative 'symbol/setter.rb' require_relative 'symbol/succ.rb' require_relative 'symbol/thrown.rb' require_relative 'symbol/to_proc.rb' require_relative 'symbol/variablize.rb' facets-2.9.3/lib/core/facets/class.rb0000644000004100000410000000060711714455226017431 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'class/descendants.rb' #require_relative 'class/hierarchically' # uncommon require_relative 'class/methodize.rb' require_relative 'class/pathize.rb' #require_relative 'class/preallocate.rb' # uncommon #require_relative 'class/singleton.rb' # uncommon require_relative 'class/subclasses.rb' require_relative 'class/to_proc.rb' facets-2.9.3/lib/core/facets/instance.rb0000644000004100000410000000534211714455226020131 0ustar www-datawww-datamodule Kernel INSTANCES = {} # Returns an instance of Instance for +self+, # which allows convenient access to an object's # internals. def instance INSTANCES[self] ||= Instance.new(self) end end # = Instance Class # # class Friend # attr_accessor :name, :age, :phone # def initialize(name, age, phone) # @name, @age, @phone = name, age, phone # end # end # # f1 = Friend.new("John", 30, "555-1212") # f1.instance # # f1.instance.update({:name=>'Jerry'}) # f1.instance # class Instance include Enumerable # def initialize(delegate) @delegate = delegate end # def instance_delegate @delegate end # def each @delegate.instance_variables.each do |name| yield(name[1..-1].to_sym, @delegate.instance_variable_get(name)) end end # Return instance variables with values as a hash. # # class X # def initialize(a,b) # @a, @b = a, b # end # end # # x = X.new(1,2) # # x.instance.to_h #=> { :a=>1, :b=>2 } # def to_h(at=false) h = {} if at @delegate.instance_variables.each do |name| h[name] = @delegate.instance_variable_get(name) end else each do |key, value| h[key] = value end end h end # TODO: Not sure if this should be used. alias_method :to_hash, :to_h # def [](name) name = atize(name) @delegate.instance_variable_get(name) end # def []=(name, value) name = atize(name) @delegate.instance_variable_set(name,value) end # def <<(pair) name, value = *pair name = atize(name) @delegate.instance_variable_set(name, value) end # Set instance variables given a +hash+. # # instance.update('@a'=>1, '@b'=>2) # @a #=> 1 # @b #=> 2 # # Also, +@+ sign is not neccessary. # # instance.update(:a=>1, :b=>2) # @a #=> 1 # @b #=> 2 # def update(hash) hash.each do |pair| self << pair end end # A hold-over from the the old #instance_assign method. alias_method :assign, :update # Same as #instance_variables. def variables @delegate.instance_variables end # Instance vairable names as symbols. def keys @delegate.instance_variables.collect do |name| name[1..-1].to_sym end end # Instance variable names as strings. def names @delegate.instance_variables.collect do |name| name[1..-1] end end # Instance variable values. def values @delegate.instance_variables.collect do |name| @delegate.instance_variable_get(name) end end # Instance evaluation. def eval(*a,&b) @delegate.instance_eval(*a,&b) end private def atize(name) name.to_s !~ /^@/ ? "@#{name}" : name end end facets-2.9.3/lib/core/facets/time/0000755000004100000410000000000011714455226016732 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/time/in.rb0000644000004100000410000000003411714455226017662 0ustar www-datawww-datarequire 'facets/time/shift' facets-2.9.3/lib/core/facets/time/set.rb0000644000004100000410000000120511714455226020050 0ustar www-datawww-dataclass Time # Like change but does not reset earlier times. # # NOTE: It would be better, probably if this were called "change". # and that #change were called "reset". # def set(options) opts={} options.each_pair do |k,v| k = :min if k.to_s =~ /^min/ k = :sec if k.to_s =~ /^sec/ opts[k] = v.to_i end self.class.send( self.utc? ? :utc : :local, opts[:year] || self.year, opts[:month] || self.month, opts[:day] || self.day, opts[:hour] || self.hour, opts[:min] || self.min, opts[:sec] || self.sec, opts[:usec] || self.usec ) end end facets-2.9.3/lib/core/facets/time/past.rb0000644000004100000410000000003511714455226020224 0ustar www-datawww-datarequire 'facets/time/future' facets-2.9.3/lib/core/facets/time/change.rb0000644000004100000410000000301111714455226020477 0ustar www-datawww-dataclass Time # Returns a new Time where one or more of the elements # have been changed according to the +options+ parameter. # The time options (hour, minute, sec, usec) reset # cascadingly, so if only the hour is passed, then # minute, sec, and usec is set to 0. If the hour and # minute is passed, then sec and usec is set to 0. # # t1 = Time.at(10000) # t1.ctime #=> "Wed Dec 31 21:46:40 1969" # # t2 = t1.change(:hour => 11) # t2.ctime #=> "Wed Dec 31 11:00:00 1969" # def change(options) opts=options; #{}; options.each_pair{ |k,v| opts[k] = v.to_i } self.class.send( self.utc? ? :utc : :local, opts[:year] || self.year, opts[:month] || self.month, opts[:day] || self.day, opts[:hour] || self.hour, opts[:min] || (opts[:hour] ? 0 : self.min), opts[:sec] || ((opts[:hour] || opts[:min]) ? 0 : self.sec), opts[:usec] || ((opts[:hour] || opts[:min] || opts[:sec]) ? 0 : self.usec) ) end # Old Version ... # # def change(options) # ::Time.send( # self.utc? ? :utc_time : :local_time, # options[:year] || self.year, # options[:month] || self.month, # options[:day] || self.day, # options[:hour] || self.hour, # options[:min] || (options[:hour] ? 0 : self.min), # options[:sec] || ((options[:hour] || options[:min]) ? 0 : self.sec), # options[:usec] || ((options[:hour] || options[:min] || options[:sec]) ? 0 : self.usec) # ) # end end facets-2.9.3/lib/core/facets/time/less.rb0000644000004100000410000000003411714455226020222 0ustar www-datawww-datarequire 'facets/time/shift' facets-2.9.3/lib/core/facets/time/future.rb0000644000004100000410000000023111714455226020565 0ustar www-datawww-dataclass Time # def past?(other=nil) self < (other || ::Time.now) end # def future?(other=nil) self > (other || ::Time.now) end end facets-2.9.3/lib/core/facets/time/hence.rb0000644000004100000410000000003111714455226020333 0ustar www-datawww-datarequire 'facets/time/in' facets-2.9.3/lib/core/facets/time/dst_adjustment.rb0000644000004100000410000000111111714455226022301 0ustar www-datawww-dataclass Time unless method_defined?(:dst_adjustment) # Adjust DST # # TODO: Can't seem to get this to pass ActiveSupport tests, # even though it is essentially identical to the ActiveSupport # code (see Time#since in time/calculations.rb). It handles # all but 4 tests. def dst_adjustment(time) self_dst = self.dst? ? 1 : 0 time_dst = time.dst? ? 1 : 0 seconds = (self - time).abs if (seconds >= 86400 && self_dst != time_dst) time + ((self_dst - time_dst) * 60 * 60) else time end end end end facets-2.9.3/lib/core/facets/time/shift.rb0000644000004100000410000000573011714455226020401 0ustar www-datawww-datarequire 'facets/time/set' require 'facets/time/dst_adjustment' class Time # TODO: Deprecate use of #dst-adjustment in Time#shift ? # Returns a new Time representing the time shifted by the time-units given. # Positive number shift the time forward, negative number shift the time # backward. # # t = Time.utc(2010,10,10,0,0,0) # t.shift( 4, :days) #=> Time.utc(2010,10,14,0,0,0) # t.shift(-4, :days) #=> Time.utc(2010,10,6,0,0,0) # # More than one unit of time can be given. # # t.shift(4, :days, 3, :hours) #=> Time.utc(2010,10,14,3,0,0) # # The #shift method can also take a hash. # # t.shift(:days=>4, :hours=>3) #=> Time.utc(2010,10,14,3,0,0) # def shift(*time_units) time_hash = Hash===time_units.last ? time_units.pop : {} time_units = time_units.flatten time_units << :seconds if time_units.size % 2 == 1 time_hash.each{ |units, number| time_units << number; time_units << units } time = self time_units.each_slice(2) do |number, units| #next time = time.ago(-number, units) if number < 0 time = ( case units.to_s.downcase.to_sym when :years, :year time.set( :year=>(year + number) ) when :months, :month if number > 0 new_month = ((month + number - 1) % 12) + 1 y = (number / 12) + (new_month < month ? 1 : 0) time.set(:year => (year + y), :month => new_month) else number = -number new_month = ((month - number - 1) % 12) + 1 y = (number / 12) + (new_month > month ? 1 : 0) time.set(:year => (year - y), :month => new_month) end when :weeks, :week time + (number * 604800) when :days, :day time + (number * 86400) when :hours, :hour time + (number * 3600) when :minutes, :minute, :mins, :min time + (number * 60) when :seconds, :second, :secs, :sec, nil time + number else raise ArgumentError, "unrecognized time units -- #{units}" end ) end dst_adjustment(time) end # Alias for #shift. alias_method :in, :shift # Alias for #shift. alias_method :hence, :shift unless method_defined?(:hence) # Returns a new Time representing the time a number of time-units ago. # This is just like #shift, but reverses the direction. # # t = Time.utc(2010,10,10,0,0,0) # # t.less(4, :days) #=> Time.utc(2010,10,6,0,0,0) # def less(*time_units) time_hash = Hash===time_units.last ? time_units.pop : {} time_units = time_units.flatten time_units << :seconds if time_units.size % 2 == 1 time_hash.each{ |units, number| time_units << number; time_units << units } neg_times = [] time_units.each_slice(2){ |number, units| neg_times << -number; neg_times << units } shift(*neg_times) end # Alias for #less alias_method :ago, :less unless method_defined?(:ago) end facets-2.9.3/lib/core/facets/time/trunc.rb0000644000004100000410000000032211714455226020407 0ustar www-datawww-dataclass Time # Truncate time at give range (in seconds). # # t = Time.now # t = t.trunc(60*60) # t.min #=> 0 # t.sec #=> 0 # def trunc(amount) self - (self.to_i % amount) end end facets-2.9.3/lib/core/facets/time/ago.rb0000644000004100000410000000003411714455226020022 0ustar www-datawww-datarequire 'facets/time/shift' facets-2.9.3/lib/core/facets/time/elapse.rb0000644000004100000410000000040711714455226020531 0ustar www-datawww-dataclass Time # Tracks the elapse time of a code block. # # e = Time.elapse { sleep 1 } # # e.assert > 1 # # CREDIT: Hal Fulton def self.elapse raise "Need block" unless block_given? t0 = now.to_f yield now.to_f - t0 end end facets-2.9.3/lib/core/facets/time/stamp.rb0000644000004100000410000000202511714455226020402 0ustar www-datawww-dataclass Time # TODO: Time::Formats need improvement! unless const_defined?('FORMAT') FORMAT = { :utc => "%Y-%m-%d %H:%M:%S", :utcT => "%Y-%m-%dT%H:%M:%S", :db => "%Y-%m-%d %H:%M:%S", :database => "%Y-%m-%d %H:%M:%S", :number => "%Y%m%d%H%M%S", :short => "%d %b %H:%M", :time => "%H:%M", :long => "%B %d, %Y %H:%M", :day1st => "%d-%m-%Y %H:%M", :dmYHM => "%d-%m-%Y %H:%M", :rfc822 => "%a, %d %b %Y %H:%M:%S %z", :ruby18 => "%a %b %d %H:%M:%S %z %Y", nil => "%Y-%m-%d %H:%M:%S %z" } end # Produce time stamp for Time.now. See #stamp. # # CREDIT: Trans def self.stamp(*args) now.stamp(*args) end # Create a time stamp. # # t = Time.at(10000) # t.stamp(:short) #=> "31 Dec 21:46" # # Supported formats come from the Time::FORMAT constant. # # CREDIT: Trans def stamp(fmt = nil) unless String === fmt fmt = FORMAT[fmt] end strftime(fmt).strip end end facets-2.9.3/lib/core/facets/time/to_time.rb0000644000004100000410000000055111714455226020720 0ustar www-datawww-dataclass Time unless method_defined?(:to_time) # 1.9 # To be able to keep Dates and Times interchangeable # on conversions. def to_time getlocal end # A method to keep Time, Date and DateTime instances interchangeable # on conversions. In this case, it simply returns +self+. #def to_time # self #end end end facets-2.9.3/lib/core/facets/time/round_to.rb0000644000004100000410000000055411714455226021114 0ustar www-datawww-datarequire 'facets/time/trunc' class Time # Round time at the nearest range (in seconds). # # t1 = Time.now # t2 = t1.round_to(60*60) # t2.min #=> 0 # t2.sec #=> 0 # # TODO: What about `round(:minute)`? # # TODO: Fractional seconds should round the usec. # def round_to(seconds) (self + seconds / 2.0).trunc(seconds) end end facets-2.9.3/lib/core/facets/float/0000755000004100000410000000000011714455226017101 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/float/round.rb0000644000004100000410000000004011714455226020547 0ustar www-datawww-datarequire 'facets/numeric/round' facets-2.9.3/lib/core/facets/module/0000755000004100000410000000000011714455226017261 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/module/remove.rb0000644000004100000410000000003611714455226021102 0ustar www-datawww-datarequire 'facets/module/nodef' facets-2.9.3/lib/core/facets/module/set.rb0000644000004100000410000000163411714455226020405 0ustar www-datawww-dataclass Module unless method_defined?(:set) # Sets an option to the given value. If the value is a proc, # the proc will be called every time the option is accessed. # # CREDIT: Blake Mizerany (Sinatra) def set(option, value=self, &block) raise ArgumentError if block && value != self value = block if block if value.kind_of?(Proc) if value.arity == 1 yield self else (class << self; self; end).module_eval do define_method(option, &value) define_method("#{option}?"){ !!__send__(option) } define_method("#{option}="){ |val| set(option, Proc.new{val}) } end end elsif value == self option.each{ |k,v| set(k, v) } elsif respond_to?("#{option}=") __send__("#{option}=", value) else set(option, Proc.new{value}) end self end end end facets-2.9.3/lib/core/facets/module/mattr.rb0000644000004100000410000001501211714455226020734 0ustar www-datawww-dataclass Module # Creates a class-variable attribute that can # be accessed both on an instance and class level. # # class CARExample # @@a = 10 # cattr :a # end # # CARExample.a #=> 10 # CARExample.new.a #=> 10 # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # CREDIT: David Heinemeier Hansson # # @uncommon # require 'facets/module/cattr' # def cattr(*syms) writers, readers = syms.flatten.partition{ |a| a.to_s =~ /=$/ } writers = writers.map{ |e| e.to_s.chomp('=').to_sym } ##readers.concat( writers ) # writers also get readers cattr_reader(*readers) cattr_writer(*writers) return readers + writers end # Creates a class-variable attr_reader that can # be accessed both on an instance and class level. # # class CARExample # @@a = 10 # cattr_reader :a # end # # CARExample.a #=> 10 # CARExample.new.a #=> 10 # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # CREDIT: David Heinemeier Hansson # # @uncommon # require 'facets/module/cattr' # def cattr_reader(*syms) syms.flatten.each do |sym| module_eval(<<-EOS, __FILE__, __LINE__) unless defined? @@#{sym} @@#{sym} = nil end def self.#{sym} @@#{sym} end def #{sym} @@#{sym} end EOS end return syms end # Creates a class-variable attr_writer that can # be accessed both on an instance and class level. # # class CAWExample # cattr_writer :a # def self.a # @@a # end # end # # CAWExample.a = 10 # CAWExample.a #=> 10 # CAWExample.new.a = 29 # CAWExample.a #=> 29 # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # CREDIT: David Heinemeier Hansson # # @uncommon # require 'facets/module/cattr' # def cattr_writer(*syms) syms.flatten.each do |sym| module_eval(<<-EOS, __FILE__, __LINE__) unless defined? @@#{sym} @@#{sym} = nil end def self.#{sym}=(obj) @@#{sym} = obj end def #{sym}=(obj) @@#{sym}=(obj) end EOS end return syms end # Creates a class-variable attr_accessor that can # be accessed both on an instance and class level. # # class CAAExample # cattr_accessor :a # end # # CAAExample.a = 10 # CAAExample.a #=> 10 # mc = CAAExample.new # mc.a #=> 10 # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # CREDIT: David Heinemeier Hansson # # @uncommon # require 'facets/module/cattr' # def cattr_accessor(*syms) cattr_reader(*syms) + cattr_writer(*syms) end # Creates a class-variable attribute that can # be accessed both on an instance and class level. # # c = Class.new do # mattr :a # def initialize # @@a = 10 # end # end # # c.new.a #=> 10 # c.a #=> 10 # # NOTE: The #mattr methods may not be as useful for modules as the #cattr # methods are for classes, becuase class-level methods are not "inherited" # across the metaclass for included modules. # # NOTE: This methiod is not a common core extension and is not # loaded automatically when using require 'facets'. # # CREDIT: David Heinemeier Hansson # # @uncommon # require 'facets/module/cattr' # def mattr(*syms) writers, readers = syms.flatten.partition{ |a| a.to_s =~ /=$/ } writers = writers.collect{ |e| e.to_s.chomp('=').to_sym } ##readers.concat( writers ) # writers also get readers mattr_writer( *writers ) mattr_reader( *readers ) return readers + writers end # Creates a class-variable attr_reader that can # be accessed both on an instance and class level. # # c = Class.new do # @@a = 10 # mattr_reader :a # end # # c.a #=> 10 # c.new.a #=> 10 # # NOTE: This methiod is not a common core extension and is not # loaded automatically when using require 'facets'. # # CREDIT: David Heinemeier Hansson # # @uncommon # require 'facets/module/cattr' # def mattr_reader( *syms ) syms.flatten.each do |sym| module_eval(<<-EOS, __FILE__, __LINE__) unless defined? @@#{sym} @@#{sym} = nil end def self.#{sym} @@#{sym} end def #{sym} @@#{sym} end EOS end return syms end # Creates a class-variable attr_writer that can # be accessed both on an instance and class level. # # c = Class.new do # mattr_writer :a # def self.a # @@a # end # end # # c.a = 10 # c.a #=> 10 # # c.new.a = 29 # c.a #=> 29 # # NOTE: This methiod is not a common core extension and is not # loaded automatically when using require 'facets'. # # CREDIT: David Heinemeier Hansson # # @uncommon # require 'facets/module/cattr' # def mattr_writer(*syms) syms.flatten.each do |sym| module_eval(<<-EOS, __FILE__, __LINE__) unless defined? @@#{sym} @@#{sym} = nil end def self.#{sym}=(obj) @@#{sym} = obj end def #{sym}=(obj) @@#{sym}=(obj) end EOS end return syms end # Creates a class-variable attr_accessor that can # be accessed both on an instance and class level. # # c = Class.new do # mattr_accessor :a # end # # c.a = 10 # c.a #=> 10 # # x = c.new # x.a #=> 10 # # NOTE: This methiod is not a common core extension and is not # loaded automatically when using require 'facets'. # # CREDIT: David Heinemeier Hansson # # @uncommon # require 'facets/module/cattr' # def mattr_accessor(*syms) mattr_reader(*syms) + mattr_writer(*syms) end end # Consider the issue where a module's metaclass is not inherited. # # m = Module.new do # @@a = 10 # mattr_reader :a # end # # c = Class.new do # include m # end # # expect NoMethodError do # c.a # end # # Ideally this would work. facets-2.9.3/lib/core/facets/module/basename.rb0000644000004100000410000000117511714455226021365 0ustar www-datawww-dataclass Module # Returns the root name of the module/class. # # module ::BaseName # class Example # end # end # # BaseName::Example.name #=> "BaseName::Example" # BaseName::Example.basename #=> "Example" # # For anonymous modules this will provide a basename # based on Module#inspect. # # m = Module.new # m.inspect # "#" # m.basename # "Module_0xb7bb0434" # # CREDIT: Trans def basename if name and not name.empty? name.gsub(/^.*::/, '') else nil #inspect.gsub('#<','').gsub('>','').sub(':', '_') end end end facets-2.9.3/lib/core/facets/module/alias_accessor.rb0000644000004100000410000000153111714455226022561 0ustar www-datawww-dataclass Module private # As with alias_method, but alias both reader and writer. # # attr_accessor :x # self.x = 1 # alias_accessor :y, :x # y #=> 1 # self.y = 2 # x #=> 2 # def alias_accessor(*args) orig = args.last args = args - [orig] args.each do |name| alias_method(name, orig) alias_method("#{name}=", "#{orig}=") end end # As with alias_accessor, but just for the reader. # This is basically the same as alias_method. # def alias_reader(*args) orig = args.last args = args - [orig] args.each do |name| alias_method(name, orig) end end # As with alias_method but does the writer instead. # def alias_writer(*args) orig = args.last args = args - [orig] args.each do |name| alias_method("#{name}=", "#{orig}=") end end end facets-2.9.3/lib/core/facets/module/instance_method_defined.rb0000644000004100000410000000113411714455226024427 0ustar www-datawww-dataclass Module # Query whether a public instance method is defined for the module. # # CREDIT: Gavin Sinclair, Noah Gibbs def instance_method_defined?(meth) instance_methods(true).find{ |m| m.to_sym == meth.to_sym } end # Query whether a normal (singleton) method is defined for the module. # # CREDIT: Gavin Sinclair, Noah Gibbs def singleton_method_defined?(meth) singleton_methods(true).find{ |m| m.to_sym == meth.to_sym } end # alias_method :module_method_defined?, :singleton_method_defined? alias_method :class_method_defined?, :singleton_method_defined? end facets-2.9.3/lib/core/facets/module/abstract.rb0000644000004100000410000000064111714455226021412 0ustar www-datawww-dataclass Module # Create an abstract method. If it is not overridden, it will # raise a TypeError when called. # # class AbstractExample # abstract :a # end # # c = AbstractExample.new # # expect TypeError do # c.a # end # # CREDIT: Trans def abstract(*sym) sym.each do |s| define_method(s){ raise TypeError, "undefined abstraction ##{s}" } end end end facets-2.9.3/lib/core/facets/module/spacename.rb0000644000004100000410000000071011714455226021540 0ustar www-datawww-dataclass Module # Returns the name of module's container module. # # module ::SpaceName # class Example # end # end # # SpaceName::Example.name #=> "SpaceName::Example" # SpaceName::Example.spacename #=> "SpaceName" # # This used to be called +dirname+. # # See also Module#basename. # # CREDIT: Trans def spacename name[0...(name.rindex('::') || 0)] #name.gsub(/::[^:]*$/, '') end end facets-2.9.3/lib/core/facets/module/attr_setter.rb0000644000004100000410000000157311714455226022154 0ustar www-datawww-dataclass Module # Create an attribute method for both getting # and setting an instance variable: # # attr_setter :a # # is equivalent to: # # def a(*args) # if args.size > 0 # @a = args[0] # self # else # @a # end # end # # CREDIT: Trans def attr_setter(*args) code, made = '', [] args.each do |a| code << %{ def #{a}(*args) args.size > 0 ? ( @#{a}=args[0] ; self ) : @#{a} end } made << "#{a}".to_sym end module_eval code made end # Alias an accessor. This create an alias for # both a reader and a writer. # # class AttrSetterExample # attr_setter :a # alias_setter :b, :a # end # # x = AttrSetterExample.new # x.b(1) # x.a #=> 1 # # CREDIT: Trans alias_method :alias_setter, :alias_method end facets-2.9.3/lib/core/facets/module/class_accessor.rb0000644000004100000410000000172111714455226022576 0ustar www-datawww-dataclass Module # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # @uncommon # require 'facets/module/class_accessor' # def class_accessor(name) class_reader(name) class_writer(name) end # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # @uncommon # require 'facets/module/class_reader' # def class_reader(name) module_eval(<<-EOS, __FILE__, __LINE__) def self.#{name} @#{name} end EOS end # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # @uncommon # require 'facets/module/class_writer' # def class_writer(name) module_eval(<<-EOS, __FILE__, __LINE__) def self.#{name}=(x) @#{name} = x end EOS end end facets-2.9.3/lib/core/facets/module/housing.rb0000644000004100000410000000003511714455226021260 0ustar www-datawww-datarequire 'facets/module/home' facets-2.9.3/lib/core/facets/module/copy_inheritor.rb0000644000004100000410000000207411714455226022646 0ustar www-datawww-datarequire 'facets/module/class_extend' class Module # Like #class_inheritor but non-dynamic. The value of the inheritor # is copied from the ancestor on first read. # # c = Class.new do # def self.x; ['x']; end # end # # d = Class.new(c) do # copy_inheritor :x # end # # d.x #=> ['x'] # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # CREDIT: Thomas Sawyer # # @uncommon # require 'facets/module/copy_inheritor' # def copy_inheritor(name, default={}) class_extend do define_method(name) do if instance_variable_defined?("@#{name}") instance_variable_get("@#{name}") else if anc = ancestors[1..-1].find{ |a| a.respond_to?(name) } value = anc.__send__(name) value = value.dup rescue value instance_variable_set("@#{name}", value) else instance_variable_set("@#{name}", default) end end end end end end facets-2.9.3/lib/core/facets/module/include_function_module.rb0000644000004100000410000000066711714455226024514 0ustar www-datawww-dataclass Module private # Include module and apply module_fuction to the # included methods. # # module Utils # module_function # def foo; "foo"; end # end # # module UtilsPlus # include_function_module Utils # end # # CREDIT: Trans def include_function_module *mod include(*mod) module_function(*mod.collect{|m| m.private_instance_methods & m.methods(false)}.flatten) end end facets-2.9.3/lib/core/facets/module/op_sub.rb0000644000004100000410000000003311714455226021071 0ustar www-datawww-datarequire 'facets/module/op' facets-2.9.3/lib/core/facets/module/attr_validator.rb0000644000004100000410000000216311714455226022627 0ustar www-datawww-dataclass Module # Like attr_writer, but the writer method validates the # setting against the given block. # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # CREDIT: ? # # @uncommon # require 'facets/module/attr_validator' # def attr_validator(*symbols, &validator) made = [] symbols.each do |symbol| define_method "#{symbol}=" do |val| unless validator.call(val) raise ArgumentError, "Invalid value provided for #{symbol}" end instance_variable_set("@#{symbol}", val) end made << "#{symbol}=".to_sym end made end # Create aliases for validator attribute methods. # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # @uncommon # require 'facets/module/attr_validator' # def alias_validator(*args) orig = args.last args = args - [orig] args.each do |name| #alias_method(name, orig) alias_method("#{name}=", "#{orig}=") end end end facets-2.9.3/lib/core/facets/module/enclosures.rb0000644000004100000410000000004211714455226021764 0ustar www-datawww-datarequire 'facets/module/enclosure' facets-2.9.3/lib/core/facets/module/class_extend.rb0000644000004100000410000000435311714455226022267 0ustar www-datawww-dataclass Module # Normally when including modules, class/module methods are not # extended. To achieve this behavior requires some clever # Ruby Karate. Instead #class_extend provides an easy to use # and clean solution. Simply place the extending class methods # in a block of the special module method #class_extend. # # module Mix # def inst_meth # puts 'inst_meth' # end # # class_extend do # def class_meth # "Class Method!" # end # end # end # # class X # include Mix # end # # X.class_meth #=> "Class Method!" # # NOTE: This old #class_extension version of this method # did not extend the containing class automatically --it had # to be done by hand. With #class_extend, that is no longer # the case. # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # CREDIT: Daniel Schierbeck, Thomas Sawyer # # THANKS: Nobu Nakada, Ulysses # # @uncommon # require 'facets/module/class_extend' # def class_extend(*mods, &block) class_extension = Module.new class_extension.__send__(:include, *mods) class_extension.module_eval(&block) if block_given? extend(class_extension) # extend this module too append_method = method(:append_features) (class << self; self; end).class_eval do define_method(:append_features) do |mod| append_method.call(mod) mod.extend(class_extension) if mod.instance_of?(Module) mod.__send__(:class_extend, class_extension) end end end class_extensions << class_extension end #private :class_extend # def class_extensions @class_extensions ||= [] end end class Class # For Class, Module#class_extend is similar to class_eval. # # The alternative is to "undef_method :class_extend", # but this seems uneccessarily limited. # # @uncommon # require 'facets/module/class_extend' # def class_extend(*mods, &block) class_extension = Module.new class_extension.__send__(:include, *mods) class_extension.module_eval(&block) if block extend(class_extension) class_extensions << class_extension end end facets-2.9.3/lib/core/facets/module/extend.rb0000644000004100000410000000003711714455226021075 0ustar www-datawww-datarequire 'facets/kernel/extend' facets-2.9.3/lib/core/facets/module/class_def.rb0000644000004100000410000000004411714455226021527 0ustar www-datawww-datarequire 'facets/module/module_def' facets-2.9.3/lib/core/facets/module/alias_module_function.rb0000644000004100000410000000103211714455226024145 0ustar www-datawww-dataclass Module private # Alias a module function so that the alias is also # a module function. The typical #alias_method # does not do this. # # module AliasExample # module_function # def hello # "Hello" # end # end # # AliasExample.hello #=> 'Hello' # # module AliasExample # alias_module_function( :hi , :hello ) # end # # AliasExample.hi #=> 'Hello' # def alias_module_function(new, old) alias_method(new, old) module_function(new) end end facets-2.9.3/lib/core/facets/module/nodef.rb0000644000004100000410000000062711714455226020706 0ustar www-datawww-dataclass Module # Alias for undef_method. This has been called "nodef" instead of # undef to help clarify that it doesn't get rid of the method, but # rather represses repsonse. alias_method :nodef, :undef_method # Alias for remove_method. This method actually "undefines" a method # and will raise an error is the method is not defined in receiver. alias_method :remove, :remove_method end facets-2.9.3/lib/core/facets/module/home.rb0000644000004100000410000000434511714455226020544 0ustar www-datawww-dataclass Module # Returns the module or class containing the receiver. # # module ::HomeExample # module M # module N # end # end # end # # HomeExample::M::N.home #=> HomeExample::M # # The home of a top-level module/class is Object. # # HomeExample.home #=> Object # # This method is called *home* because techinally a module or class # is just a constant reference, and as such can reside with multiple # namespaces, like any variable. For example: # # module OtherPlace # M = ::HomeExample::M # end # # In this example, you might think that +OtherPlace::M+'s home would be # +OtherPlace+, but +OtherPlace::M+ is the same object as +HomeExample::M+, # and it can have only one "home" --the original location of it's definition. def home #homename = /::[^:]+\Z/ =~ name ? $` : nil if homename homename.split(/::/).inject(self) do |mod, cref| if /\:(0x.*?)\>$/ =~ cref # TODO: does this ever happen? #p $1.to_i(16) ObjectSpace._idref($1.to_i(16)) else mod.const_get(cref) end end else Object end end # Returns the name of module or class containing the receiver. # # module ::HomeExample # module M # module N # end # end # end # # HomeExample::M::N.homename #=> "HomeExample::M" # # See also Module#basename. def homename /::[^:]+\Z/ =~ name ? $` : nil end # Original name for #homename. alias_method :modname, :homename # Returns all the namespaces of this module according ordered from # nearest and moving outwards. The receiver is not contained within # the result. # # module ::HouseExample # module M # module N # end # end # end # # HouseExample.housing #=> [Object] # HouseExample::M.housing #=> [HouseExample, Object] # HouseExample::M::N.housing #=> [HouseExample::M, HouseExample, Object] # # Compare this to +Module.nesting+. def housing n = [] name.split(/::/).inject(self) do |mod, cref| c = mod.const_get(cref) ; n.unshift(c) ; c end n << Object # ? n.shift # we really don't need +self+ too. n end end facets-2.9.3/lib/core/facets/module/op_mul.rb0000644000004100000410000000003311714455226021075 0ustar www-datawww-datarequire 'facets/module/op' facets-2.9.3/lib/core/facets/module/pathize.rb0000644000004100000410000000053511714455226021255 0ustar www-datawww-datarequire 'facets/string/pathize' class Module # Converts a class name to a unix path. # # module ::ExamplePathize # module Example # end # end # # ExamplePathize.pathize #=> "example_pathize" # ExamplePathize::Example.pathize #=> "example_pathize/example" # def pathize name.pathize end end facets-2.9.3/lib/core/facets/module/enclosure.rb0000644000004100000410000000437411714455226021615 0ustar www-datawww-dataclass Module # Returns the module which contains this one according to its name. # # module ::EncExample # module M # module N # end # end # end # # EncExample::M::N.enclosure #=> EncExample::M # # The enclosure of top-level and anonymous modules is Object. # # EncExample.enclosure #=> Object # Module.new.enclosure #=> Object # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # @uncommon # require 'facets/module/enclosure' # def enclosure name = /::[^:]+\Z/ =~ self.name ? $` : nil if name #base = name.sub!(/^::/, '') ? Object : self name.split(/::/).inject(self) do |mod, cref| if /\:(0x.*?)\>$/ =~ cref # TODO: does this ever happen? #p $1.to_i(16) ObjectSpace._idref($1.to_i(16)) else mod.const_get(cref) end end else Object end end # Returns all the namespaces of this module according ordered from # nearest and moving outwards. The receiver is not contained within # the result. # # module ::EncExample # module M # module N # end # end # end # # EncExample.enclosures #=> [Object] # EncExample::M.enclosures #=> [EncExample, Object] # EncExample::M::N.enclosures #=> [EncExample::M, EncExample, Object] # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # @uncommon # require 'facets/module/enclosures' # def enclosures n = [] name.split(/::/).inject(self) do |mod, cref| c = mod.const_get(cref) ; n.unshift(c) ; c end n << Object # ? n.shift # we really don't need +self+ too. n end # Enclosure name. # # module ::EncExample # module M # module N # end # end # end # # EncExample::M::N.encname #=> "EncExample::M" # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # @uncommon # require 'facets/module/enclosure' # def encname /::[^:]+\Z/ =~ self.name ? $` : nil end end facets-2.9.3/lib/core/facets/module/attr_class_accessor.rb0000644000004100000410000000215611714455226023633 0ustar www-datawww-dataclass Module # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # @uncommon # require 'facets/module/attr_class_accessor' # def attr_class_accessor(name) attr_class_reader(name) attr_class_writer(name) end # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # @uncommon # require 'facets/module/attr_class_reader' # def attr_class_reader(name) module_eval(<<-EOS, __FILE__, __LINE__) def self.#{name} @#{name} end def #{name} self.class.#{name} end EOS end # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # @uncommon # require 'facets/module/attr_class_writer' # def attr_class_writer(name) module_eval(<<-EOS, __FILE__, __LINE__) def self.#{name}=(x) @#{name} = x end def #{name}=(x) self.class.#{name} = x end EOS end end facets-2.9.3/lib/core/facets/module/to_obj.rb0000644000004100000410000000041511714455226021062 0ustar www-datawww-dataclass Module # Create an instance of Object and extend it with +self+. # # mod = Module.new do # def foo; "foo"; end # end # # obj = mod.to_obj # # obj.foo #=> "foo" # def to_obj o = Object.new o.extend self o end end facets-2.9.3/lib/core/facets/module/preextend.rb0000644000004100000410000000111611714455226021603 0ustar www-datawww-dataclass Module # Prepend an +aspect+ module to a module. # This only works at the module level. # # module ::PreX # def x; "x"; end # end # # module ::PreU # def x; '{' + super + '}'; end # end # # PreX.preextend(PreU) # # PreX.x # => "{x}" # # NOTE: This is not a common core extension and is not loaded # automatically when using require 'facets'. # # CREDIT Trans # # @uncommon # require 'facets/module/preextend' # def preextend(aspect) aspect.__send__(:include, self) extend aspect end end facets-2.9.3/lib/core/facets/module/class_inheritor.rb0000644000004100000410000000414511714455226023002 0ustar www-datawww-datarequire 'facets/module/class_extend' class Module # = Class Inheritor # # Create an dynamic class inheritable attribute. # # Inheritor providse a means to store and inherit data via the class # heirarchy. An inheritor creates two methods one named after the key # that provides a reader. And one named after key! which provides the # writer. (Because of the unique nature of inheritor the reader and # writer can't be the same method.) # # The first argument is the inheritor's name. The second argument # is the archtype object. This object must be duplicable (via #dup). # The last argument is either the symbolic operator/method or a block # that specifies how one hierarchical level "integrates" with the next. # # class X # class_inheritor :x, [], :+ # end # # class Y < X # end # # X.x! << :a # X.x #=> [:a] # Y.x #=> [:a] # # Y.x! << :b # X.x #=> [:a] # Y.x #=> [:a, :b] # # NOTE: Adding an inheritor directly to Module or Class will probably # not do what is expected. Thankfully that usecase is likely a YAGNI, # but in anycase it is even more likely that it is not possible with # this code. # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # CREDIT: Thomas Sawyer # # @uncommon # require 'facets/module/class_inheritor' # def class_inheritor(key, obj, op=nil, &fop) raise ArgumentError if op && fop if !fop op = op ? op.to_sym : :+ fop = lambda{ |o, x| o.__send__(op, x) } end #(class << self; self; end).module_eval do class_extend do define_method(key) do ancestors.reverse.inject(obj.dup) do |o, a| if a.respond_to?("#{key}!") fop.call(o, a.__send__("#{key}!")) else o end end end define_method("#{key}!") do if instance_variable_defined?("@#{key}") instance_variable_get("@#{key}") else instance_variable_set("@#{key}", obj.dup) end end end end end facets-2.9.3/lib/core/facets/module/anonymous.rb0000644000004100000410000000105611714455226021640 0ustar www-datawww-dataclass Module # A module may or may not have a name. # # module M; end # M.name # => "M" # # m = Module.new # m.name # => "" # # A module gets a name when it is first assigned to a constant. Either # via the +module+ or +class+ keyword or by an explicit assignment: # # m = Module.new # creates an anonymous module # M = m # => m gets a name here as a side-effect # m.name # => "M" # def anonymous? # The name of an anonymous class is an empty # string in 1.8, and nil in 1.9. name.nil? || name.empty? end end facets-2.9.3/lib/core/facets/module/op_add.rb0000644000004100000410000000003311714455226021030 0ustar www-datawww-datarequire 'facets/module/op' facets-2.9.3/lib/core/facets/module/methodize.rb0000644000004100000410000000052211714455226021575 0ustar www-datawww-datarequire 'facets/string/methodize' class Module # Translate a module name to a suitable method name. # # module ::EgMethodize # module Eg # end # end # # EgMethodize.methodize #=> "eg_methodize" # EgMethodize::Eg.methodize #=> "eg_methodize__eg" # def methodize name.methodize end end facets-2.9.3/lib/core/facets/module/module_def.rb0000644000004100000410000000113711714455226021713 0ustar www-datawww-dataclass Module # Defines an instance method within a class/module. # # CREDIT: WhyTheLuckyStiff def class_def name, &blk class_eval { define_method name, &blk } end # Defines an instance method within a class/module. # # CREDIT: WhyTheLuckyStiff def module_def name, &blk module_eval { define_method name, &blk } end #-- # TODO: Why are we making these protected, # and where should these really go in Facets? #++ protected :attr protected :attr_reader protected :attr_writer protected :attr_accessor protected :remove_method protected :undef_method end facets-2.9.3/lib/core/facets/module/let.rb0000644000004100000410000000113511714455226020372 0ustar www-datawww-dataclass Module # Create a memoized method. This method has been popularized by RSpec. # # class LetExample # let(:seed) { rand } # end # # eg = LetExample.new # eg.seed == eg.seed # # CREDIT: Howard Yeh # # @uncommon # require 'facets/module/let' # def let(var,&block) name = "@#{var}" self.class_eval do define_method(var) do if instance_variable_defined?(name) instance_variable_get(name) else val = self.instance_eval(&block) instance_variable_set(name,val) end end end end end facets-2.9.3/lib/core/facets/module/alias_method_chain.rb0000644000004100000410000000331711714455226023405 0ustar www-datawww-dataclass Module # Encapsulates the common pattern of ... # # alias_method :foo_without_feature, :foo # alias_method :foo, :foo_with_feature # # With this, you simply do ... # # alias_method_chain :foo, :feature # # For example # # class AliasMethodChainExample # def foo # "foo" # end # # def foo_with_feature # "foo!" # end # # alias_method_chain :foo, :feature # end # # And both aliases are set up for you. # # example = AliasMethodChainExample.new # example.foo #=> "foo!" # example.foo_without_feature #=> "foo" # # Query and bang methods (foo?, foo!) keep the same punctuation ... # # alias_method_chain :foo?, :feature # # is equivalent to ... # # alias_method :foo_without_feature?, :foo? # alias_method :foo?, :foo_with_feature? # # so you can safely chain foo, foo?, and foo! with the same feature. # # CREDIT: Bitsweat, Rails Team def alias_method_chain(target, feature) # Strip out punctuation on predicates or bang methods since # e.g. target?_without_feature is not a valid method name. aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1 yield(aliased_target, punctuation) if block_given? with_method, without_method = "#{aliased_target}_with_#{feature}#{punctuation}", "#{aliased_target}_without_#{feature}#{punctuation}" alias_method without_method, target alias_method target, with_method case when public_method_defined?(without_method) public target when protected_method_defined?(without_method) protected target when private_method_defined?(without_method) private target end end end facets-2.9.3/lib/core/facets/module/module_load.rb0000644000004100000410000000427211714455226022077 0ustar www-datawww-dataclass Module # Load file directly into module/class namespace. # # Please use this with careful consideration. # It is best suited to loading plugin-type scripts, # and should generally not be used as a substitue for # Ruby's standard load system. # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # CREDIT: Trans # # @uncommon # require 'facets/module/module_load' # def module_load( path ) if path =~ /^[\/~.]/ file = File.expand_path(path) else $LOAD_PATH.each do |lp| file = File.join(lp,path) break if File.exist?(file) file = nil end end raise LoadError, "no such file to load -- #{path}" unless file module_eval(File.read(file)) end # Require file into module/class namespace. # # Unlike load this keeps a per-module cache and will # not load the same file into the same module more # than once despite repeated attempts. # # The cache is kept in a global var called +$module_require+. # # Please use this with careful consideration. # It is best suited to loading plugin-type scripts, # and should generally not be used as a substitue for # Ruby's standard load system. # # NOTE: This method is not a common core extension and is not loaded # automatically when using require 'facets'. # # CREDIT: Trans # # @uncommon # require 'facets/module/module_load' # def module_require( path ) if path =~ /^[\/~.]/ file = File.expand_path(path) else $LOAD_PATH.each do |lp| file = File.join(lp,path) break if File.exist?(file) file += '.rb' break if File.exist?(file) file = nil end end raise LoadError, "no such file to load -- #{path}" unless file # per-module load cache $module_require ||= {} $module_require[self] ||= {} loaded = $module_require[self] if loaded.key?(file) false else loaded[file] = true script = File.read(file) module_eval(script) true end end alias_method :class_require, :module_require alias_method :class_load, :module_load end facets-2.9.3/lib/core/facets/module/all_instance_methods.rb0000644000004100000410000000066011714455226023767 0ustar www-datawww-dataclass Module # List all instance methods, equivalent to # # public_instance_methods + # protected_instance_methods + # private_instance_methods # # TODO: Better name for #all_instance_methods? # # CREDIT: Trans def all_instance_methods(include_super=true) public_instance_methods(include_super) + protected_instance_methods(include_super) + private_instance_methods(include_super) end end facets-2.9.3/lib/core/facets/module/modname.rb0000644000004100000410000000004111714455226021221 0ustar www-datawww-datarequire 'facets/module/homename' facets-2.9.3/lib/core/facets/module/memoize.rb0000644000004100000410000000050511714455226021253 0ustar www-datawww-datarequire 'facets/memoizable' class Module # This is here for backward compatibility. # # @uncommon # require 'facets/module/memoize' # def memoize(*args) include Memoizable Memoizable.instance_method(:memoize).bind(self).call(*args) #super(*args) # TODO: why is super not working here? end end facets-2.9.3/lib/core/facets/module/instance_method.rb0000644000004100000410000000124211714455226022751 0ustar www-datawww-data$FIRST_CLASS_INSTANCE_METHODS = Hash.new{ |h,k| h[k] = {} } # class Module # Access method as a singleton object and retain state. # # module ::K # def hello # puts "Hello World!" # end # end # # K.instance_method!(:hello).inspect #=> "#" # # NOTE: This is limited to the scope of the current module/class. def instance_method!(s) #( @@__instance_methods__ ||= {} )[s] ||= instance_method(s) # TODO: use class vars for 1.9+ ? #( @__instance_methods__ ||= {} )[s.to_sym] ||= instance_method(s.to_sym) $FIRST_CLASS_INSTANCE_METHODS[self][s.to_sym] ||= instance_method(s.to_sym) end end facets-2.9.3/lib/core/facets/module/redefine_method.rb0000644000004100000410000000137511714455226022735 0ustar www-datawww-dataclass Module private # Creates a new method for a pre-existing method. # # If _aka_ is given, then the method being redefined will # first be aliased to this name. # # class Greeter # def hello ; "Hello" ; end # end # # Greeter.new.hello #=> "Hello" # # class Greeter # redefine_method( :hello, :hi ) do # hi + ", friend!" # end # end # # Greeter.new.hello #=> "Hello, friend!" # # CREDIT: Trans def redefine_method(sym, aka=nil, &blk) alias_method(aka, sym) if aka ## prevent warning about method overwrite begin remove_method(sym) rescue NameError end ## define replacelemt method define_method(sym, &blk) end # alias_method :redef, :redefine_method end facets-2.9.3/lib/core/facets/module/rename_method.rb0000644000004100000410000000111111714455226022407 0ustar www-datawww-dataclass Module private # Aliases a method and undefines the original. # # class RenameExample # def foo; "foo"; end # rename_method(:bar, :foo) # end # # example = RenameExample.new # example.bar #=> 'foo' # # expect NoMethodError do # example.foo # end # # CREDIT: Trans def rename_method( to_sym, from_sym ) raise ArgumentError, "method #{from_sym} does not exist" unless method_defined?( from_sym ) alias_method( to_sym, from_sym ) undef_method( from_sym ) end alias_method :rename, :rename_method end facets-2.9.3/lib/core/facets/module/wrap_method.rb0000644000004100000410000000140011714455226022112 0ustar www-datawww-dataclass Module #private # (we'll leave this one public for AOP-like uses). # Creates a new method wrapping the previous of the same name. # Reference to the old method is passed into the new definition # block as the first parameter. # # class WrapExample # def foo # "foo" # end # # wrap_method(:foo) do |old_meth, *args| # old_meth.call + '!' # end # end # # example = WrapExample.new # example.foo #=> 'foo!' # # Keep in mind that this cannot be used to wrap methods # that take a block. # # CREDIT: Trans def wrap_method( sym, &blk ) old = instance_method(sym) define_method(sym) { |*args| blk.call(old.bind(self), *args) } end alias_method :wrap, :wrap_method end facets-2.9.3/lib/core/facets/module/attr_tester.rb0000644000004100000410000000221711714455226022150 0ustar www-datawww-dataclass Module # Create an tester attribute. This creates a single method # used to test the attribute for truth. # # attr_tester :a # # is equivalent to # # def a? # @a ? true : @a # end # # Note that this method is not a common core extension and is not # loaded automatically when using require 'facets'. # # CREDIT: Trans # # @todo This method will probably be deprecated. # # @uncommon # require 'facets/module/attr_tester' # def attr_tester(*args) code, made = '', [] args.each do |a| code << %{ def #{a}?(truth=nil) @#{a} ? truth || @#{a} : @#{a} end } made << "#{a}?".to_sym end module_eval code made end # Create aliases for flag reader. # # Note that this method is not a common core extension and is not # loaded automatically when using require 'facets'. # # CREDIT: Trans # # @uncommon # require 'facets/module/attr_tester' # def alias_tester(*args) orig = args.last args = args - [orig] args.each do |name| alias_method("#{name}?", "#{orig}?") end end end facets-2.9.3/lib/core/facets/module/revise.rb0000644000004100000410000000143611714455226021107 0ustar www-datawww-datarequire 'facets/module/redirect_method' require 'facets/module/redefine_method' require 'facets/module/rename_method' require 'facets/module/wrap_method' require 'facets/module/nodef' class Module # Return a new module based on another. This includes the original module # into the new revised module. # # module ReviseExample # def foo; "foo"; end # end # # ReviseExample2 = ReviseExample.revise do # alias_method :bar, :foo # end # # object = Object.new # object.extend ReviseExample2 # object.bar #=> 'foo' # # CREDIT: Trans def revise(&blk) base = self nm = Module.new{ include base } nm.class_eval(&blk) nm end alias_method :revisal, :revise end class Class undef_method :revise undef_method :revisal end facets-2.9.3/lib/core/facets/module/redirect_method.rb0000644000004100000410000000173211714455226022752 0ustar www-datawww-dataclass Module private # Redirect methods to other methods. This simply # defines methods by the name of a hash key which # calls the method with the name of the hash's value. # # class RedirectExample # redirect_method :hi => :hello, :hey => :hello # def hello(name) # "Hello, #{name}." # end # end # # e = RedirectExample.new # e.hello("Bob") #=> "Hello, Bob." # e.hi("Bob") #=> "Hello, Bob." # e.hey("Bob") #=> "Hello, Bob." # # The above class definition is equivalent to ... # # class RedirectExample # def hi(*args) # hello(*args) # end # def hey(*args) # hello(*args) # end # def hello # puts "Hello" # end # end # # CREDIT: Trans def redirect_method( method_hash ) method_hash.each do |targ,adv| define_method(targ) { |*args| send(adv,*args) } end end # alias_method :redirect, :redirect_method end facets-2.9.3/lib/core/facets/module/is.rb0000644000004100000410000000215211714455226020221 0ustar www-datawww-dataclass Module # Is a given class or module an ancestor of this # class or module? # # class IsX ; end # class IsY < IsX ; end # # IsY.is?(IsX) #=> true # # CREDIT: Trans def is?(base) Module===base && ancestors.slice(1..-1).include?(base) end # An alias for #include. # # class IsExample # is Enumerable # end # # CREDIT: Trans def is(*mods) mods.each do |mod| if mod.const_defined?(:Self) extend mod::Self # pass it along if module if instance_of?(Module) const_set(:Self, Module.new) unless const_defined?(:Self) const_get(:Self).send(:include, mod::Self) end end end include(*mods) end #alias_method :is, :include # Expirmental idea for #is. # # If the module has #append_feature_function # defined, this will use that instead of #include ... # # def is(*modules) # module.each do { |m| # if m.respond_to?(:append_feature_function) # send(m.append_feature_function,m) # else # include m # end # end # end end facets-2.9.3/lib/core/facets/module/homename.rb0000644000004100000410000000003511714455226021375 0ustar www-datawww-datarequire 'facets/module/home' facets-2.9.3/lib/core/facets/module/singleton_method_defined.rb0000644000004100000410000000006011714455226024622 0ustar www-datawww-datarequire 'facets/module/instance_method_defined' facets-2.9.3/lib/core/facets/module/ancestor.rb0000644000004100000410000000034011714455226021421 0ustar www-datawww-dataclass Module # Is a given class or module an ancestor of # this class or module? # # class X ; end # class Y < X ; end # # X.ancestor?(Y) # def ancestor?( mod ) ancestors.include?(mod) end end facets-2.9.3/lib/core/facets/module/method_space.rb0000644000004100000410000000462311714455226022246 0ustar www-datawww-datarequire 'facets/functor' require 'facets/module/basename' class Module # Create method namespaces, allowing for method # chains but still accessing the object's instance. # # class A # attr_writer :x # method_space :inside do # def x; @x; end # end # end # # a = A.new # a.x = 10 # a.inside.x #=> 10 # # expect NoMethodError do # a.x # end # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # CREDIT: Pit Captain # # @uncommon # require 'facets/module/method_space' # def method_space(name, mod=nil, &blk) ## If block is given then create a module, otherwise ## get the name of the module. if block_given? name = name.to_s raise ArgumentError if mod mod = Module.new(&blk) else if Module === name mod = name name = mod.basename.downcase end mod = mod.dup end ## Include the module. This is neccessary, otherwise ## Ruby won't let us bind the instance methods. include mod ## Save the instance methods of the module and ## replace them with a "transparent" version. methods = {} mod.instance_methods(false).each do |m| methods[m.to_sym] = mod.instance_method(m) mod.module_eval %{ def #{m}(*a,&b) super(*a,&b) end } ##mod.instance_eval do ## define_method(m) ## super ## end ##end end ## Add a method for the namespace that delegates ## via the Functor to the saved instance methods. define_method(name) do mtab = methods Functor.new do |op, *args| if meth = mtab[op.to_sym] meth.bind(self).call(*args) else #self.__send__(op, *args) raise NoMethodError, "undefined method `#{m}'" end end end end # Include a module via a specified space. # # module T # def t ; "HERE" ; end # end # # class X # include_as :test => T # def t ; test.t ; end # end # # X.new.t #=> "HERE" # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # @uncommon # require 'facets/module/method_space' # def include_as(h) h.each{ |name, mod| method_space(name, mod) } end end facets-2.9.3/lib/core/facets/module/include_as.rb0000644000004100000410000000004511714455226021713 0ustar www-datawww-datarequire 'facets/module/method_space' facets-2.9.3/lib/core/facets/module/method_clash.rb0000644000004100000410000000255611714455226022250 0ustar www-datawww-dataclass Module # TODO: Should method_clash just be public methods? # TODO: Provide an option to select visiblity. # Detect method name clash between modules and/or classes, regardless of # method visibility: # # module MethodClashExample # # module A # def c; end # end # # module B # private # def c; end # end # # A.method_clash(B) #=> [:c] # # end # # CREDIT: Thomas Sawyer, Robert Dober # # @uncommon # require 'facets/module/method_clash' # def method_clash(other) common_ancestor = (ancestors & other.ancestors).first s = [] s += public_instance_methods(true) s += private_instance_methods(true) s += protected_instance_methods(true) o = [] o += other.public_instance_methods(true) o += other.private_instance_methods(true) o += other.protected_instance_methods(true) c = s & o if common_ancestor c -= common_ancestor.public_instance_methods(true) c -= common_ancestor.private_instance_methods(true) c -= common_ancestor.protected_instance_methods(true) end return c end # Uses #method_clash to return +true+ or +false+ if there # are method name clashes. # # @uncommon # require 'facets/module/method_clash' # def method_clash?(other) c = method_clash(other) !c.empty? end end facets-2.9.3/lib/core/facets/module/class.rb0000644000004100000410000000025711714455226020717 0ustar www-datawww-dataclass Module # Alias for #===. This provides a verbal method # for inquery. # # s = "HELLO" # String.class?(s) #=> true # alias_method :class?, :=== end facets-2.9.3/lib/core/facets/module/instance_function.rb0000644000004100000410000000416011714455226023320 0ustar www-datawww-dataclass Module # Converts module methods into instance methods such that the first parameter # is passed +self+. This promotes DRY programming when wishing to offer both # inheritable and module callable procedures. # # This method is modeled after +module_function+ which essentially has the the # opposite effect. Due to implementation limitations, this must use the callback # #singleton_method_added to emulate +module_function+ when no method names # are given. # # module MyModule # instance_function # # def self.jumble(obj, arg) # obj + arg # end # end # # MyModule.jumble("Try", "Me") #=> "TryMe" # # s = "Try" # s.extend MyModule # s.jumble("Me") #=> "TryMe" # # Note: This used to be a module called PromoteSelf and later Instantize, # before becoming a method. # # NOTE: This method is not a common core extension and is not # loaded automatically when using require 'facets'. # # @uncommon # require 'facets/module/instance_function' # def instance_function(*meths) this = self if meths.empty? extend InstanceFunction else meths.each do |meth| module_eval do define_method(meth) do |*args| this.__send__(meth, self, *args) end end ##class_eval %{ ## def #{meth}(*args) ## #{self.name}.#{meth}(self,*args) ## end ##} end end end module InstanceFunction #:nodoc # def singleton_method_added(meth) this = self ##module_eval %{ ## def #{meth}(*args) ## #{self.name}.#{meth}(self,*args) ## end ##} module_eval do define_method(meth) do |*args| this.__send__(meth, self, *args) end end super(meth) end end end #class Module =begin module Instantize def self.append_features(mod) mod.extend self end def singleton_method_added( meth ) d = %{ def #{meth}(*args) #{self.name}.#{meth}(self,*args) end } self.class_eval d super(meth) end end =end facets-2.9.3/lib/core/facets/module/integrate.rb0000644000004100000410000000213711714455226021573 0ustar www-datawww-datarequire 'facets/module/redirect_method' require 'facets/module/redefine_method' require 'facets/module/rename_method' require 'facets/module/wrap_method' require 'facets/module/nodef' class Module # Using integrate is just like using include except the # module included is a reconstruction of the one given # altered by the commands given in the block. # # Convenient commands available are: #rename, #redef, # #remove, #nodef and #wrap. But any module method # can be used. # # module IntegrateExampleModule # def q ; "q" ; end # def y ; "y" ; end # end # # class InegrateExampleClass # integrate IntegrateExampleModule do # undef_method :y # end # end # # x = InegrateExampleClass.new # x.q #=> "q" # # expect NameError do # x.y # end # # This is like #revisal, but #revisal only # returns the reconstructred module. It does not # include it. # # CREDIT: Trans def integrate(mod, &block) #include mod.revisal( &blk ) m = Module.new{ include mod } m.class_eval(&block) include m end end facets-2.9.3/lib/core/facets/module/class_method_defined.rb0000644000004100000410000000006011714455226023725 0ustar www-datawww-datarequire 'facets/module/instance_method_defined' facets-2.9.3/lib/core/facets/module/op.rb0000644000004100000410000000406711714455226020233 0ustar www-datawww-dataclass Module # Combine modules. # # module APlus # def a; "a"; end # end # # module BPlus # def b; "b"; end # end # # CPlus = APlus + BPlus # # class XPlus; include CPlus; end # # XPlus.new.a #=> "a" # XPlus.new.b #=> "b" # # Note that in the old version of traits.rb we cloned # modules and altered their copies... # # def +(other) # mod1 = other.clone # mod2 = clone # mod1.module_eval{ include mod2 } # end # # Later it was realized that this thwarted the main # benefit that Ruby's concept of modules has over # traditional traits, inheritance. # # CREDIT: Thomas Sawyer, Robert Dober def +(other) base = self Module.new do include base include other end end # Subtract modules. # # module AMinus # def a; "a"; end # def b; "b"; end # end # # CMinus = AMinus - [:a] # # class XMinus; include CMinus; end # # expect NameError do # XMinus.new.a #=> "a" # end # # XMinus.new.b #=> "b" # # TODO: Should this use all instance methods, not just public? # # CREDIT: Thomas Sawyer, Robert Dober def -(other) instance_methods = instance_methods(true).map{|m| m.to_sym} case other when Array subtract = instance_methods & other.map{|m| m.to_sym} when Module subtract = instance_methods & other.instance_methods(true).map{|m| m.to_sym} # false? when String, Symbol subtract = instance_methods & [other.to_sym] end base = self Module.new do include base subtract.each{ |x| undef_method x } end end # Rename methods. # # module AStar # def a; "a"; end # end # # BStar = AStar * { :a => :b } # # class XStar; include BStar; end # # XStar.new.b #=> "a" # # CREDIT: Thomas Sawyer, Robert Dober def *(rename_map) base = self Module.new do include base rename_map.each do |from, to| alias_method to, from undef_method from end end end end facets-2.9.3/lib/core/facets/module/can.rb0000644000004100000410000000044011714455226020345 0ustar www-datawww-dataclass Module # An alias for #extend. # # module EgCan # def foo; "foo"; end # end # # class EgCanClass # can EgCan # end # # EgCanClass.foo #=> 'foo' # # BTW, why is Forwardable an -able? It's not a mixin! alias_method :can, :extend end facets-2.9.3/lib/core/facets/filetest.rb0000644000004100000410000000043411714455226020141 0ustar www-datawww-datarequire 'facets/kernel/require_relative' require_relative 'filetest/absolute.rb' require_relative 'filetest/contains.rb' require_relative 'filetest/relative.rb' require_relative 'filetest/root.rb' require_relative 'filetest/safe.rb' require_relative 'filetest/separator_pattern.rb' facets-2.9.3/lib/core/facets/applique/0000755000004100000410000000000011714455226017614 5ustar www-datawww-datafacets-2.9.3/lib/core/facets/applique/file_helpers.rb0000644000004100000410000000161311714455226022603 0ustar www-datawww-data# def temporary_directory @temporary_directory ||= 'tmp' end When /Given a directory '(.*?)' containing/ do |dir, text| @temporary_directory = File.join(@temporary_directory, dir) text.lines.each do |file| next if file =~ /^\s*$/ file = File.join(@temporary_directory, file.strip) dir = File.dirname(file) FileUtils.mkdir_p(dir) File.open(file, 'w'){ |f| f << "SPINICH" } end end Before :all do if File.exist?(temporary_directory) FileUtils.rm_r(temporary_directory) end FileUtils.mkdir_p(temporary_directory) end # Used for File extensions When "had a file '(((.*?)))'" do |name| name = name.sub(/^tmp\//, '') # b/c QED now runs from tmp/qed File.open(name, 'w'){|f| f << "Hello World"} end When "had a binary file '(((.*?)))'" do |name| name = name.sub(/^tmp\//, '') # b/c QED now runs from tmp/qed File.open(name, 'wb'){|f| f << "Hello\nWorld\n"} end facets-2.9.3/lib/core/facets.yml0000644000004100000410000000255311714455226016524 0ustar www-datawww-data--- authors: - name: Thomas Sawyer email: transfire@gmail.com copyrights: - holder: Thomas Sawyer year: '2004' license: Ruby replacements: [] conflicts: [] requirements: - name: lemon groups: - test development: true - name: qed groups: - test development: true - name: detroit groups: - build development: true dependencies: [] repositories: - uri: git@github.com:rubyworks/facets.git scm: git name: upstream resources: home: http://rubyworks.github.com/facets code: http://github.com/rubyworks/facets docs: http://rubyworks.github.com/facets/learn.html wiki: http://wiki.github.com/rubyworks/facets talk: http://groups.google.com/group/facets-universal load_path: - lib/core - lib/core-uncommon - lib/standard - lib/supplemental extra: slogan: ALL YOUR BASE ARE BELONG TO RUBY! manifest: MANIFEST source: [] alternatives: [] revision: 0 title: Facets name: facets summary: Premium Ruby Extensions created: '2004-12-16' description: Facets is the premier collection of extension methods for the Ruby programming language. Facets extensions are unique by virtue of thier atomicity. They are stored in individual files allowing for highly granular control of requirements. In addition, Facets includes a few additional classes and mixins suitable to wide variety of applications. organization: rubyworks version: 2.9.2 date: '2011-08-23' facets-2.9.3/lib/standard/0000755000004100000410000000000011714455226015377 5ustar www-datawww-datafacets-2.9.3/lib/standard/facets/0000755000004100000410000000000011714455226016644 5ustar www-datawww-datafacets-2.9.3/lib/standard/facets/set.rb0000644000004100000410000000104611714455226017765 0ustar www-datawww-datarequire 'set' class Set # # @author Phrogz def power_set if empty? Set[self] else any_value = [to_a.first] subsubs = (self - any_value).power_set subsubs + subsubs.map{ |subset| subset + any_value } end end end class Array # TODO: Move to Array extensions. # # @author Phrogz def power_set if empty? [self] else subset = dup value = [ subset.pop ] subsubs = subset.power_set subsubs.concat( subsubs.map{ |subset| subset + value } ) end end end facets-2.9.3/lib/standard/facets/math/0000755000004100000410000000000011714455226017575 5ustar www-datawww-datafacets-2.9.3/lib/standard/facets/math/std.rb0000644000004100000410000000075711714455226020725 0ustar www-datawww-datarequire 'facets/math/variance' module Math # Standard deviation of a sample. # def self.std(array, &block) sqrt(variance(array, &block)) end class << self alias_method :standard_deviation, :std end # Standard deviation of a population. # def self.pstd(array, &block) Math::sqrt(pvariance(array, &block)) end # Calculates the standard error of a sample. def self.stderr(array) return 0.0 if array.size < 2 std(array) / sqrt(array.size) end end facets-2.9.3/lib/standard/facets/math/cot.rb0000644000004100000410000000012711714455226020707 0ustar www-datawww-datamodule Math # Cotangens of +x+ def self.cot(x) tan((PI * 0.5) - x) end end facets-2.9.3/lib/standard/facets/math/round.rb0000644000004100000410000000013411714455226021247 0ustar www-datawww-datamodule Math # Round number to an integer. # def self.round(x) x.round end end facets-2.9.3/lib/standard/facets/math/median.rb0000644000004100000410000000070111714455226021355 0ustar www-datawww-datarequire 'facets/math/percentile' module Math # Returns the numerical median for the an array of values; # or nil if array is empty. # def self.median(array) percentile(array, 50) end # better definition ? =begin # def self.median(array) return 0 if array.size == 0 tmp = array.sort mid = tmp.size / 2 if (tmp.size % 2) == 0 (tmp[mid-1] + tmp[mid]).to_f / 2 else tmp[mid] end end =end end facets-2.9.3/lib/standard/facets/math/csc.rb0000644000004100000410000000011711714455226020671 0ustar www-datawww-datamodule Math # Cosecans of +x+ def self.csc(x) 1.0 / sin(x) end end facets-2.9.3/lib/standard/facets/math/min.rb0000644000004100000410000000102111714455226020677 0ustar www-datawww-datamodule Math # def self.min(array, &block) if block_given? if min = array.find{ |i| i } min = yield(min) array.each do |i| j = yield(i) min = j if min > j end min end else array.min end end # def self.max(array, block) if block_given? if max = find{|i| i} max = yield(max) each{|i| j = yield(i) max = j if max < j } max end else array.max end end end facets-2.9.3/lib/standard/facets/math/gini_coefficient.rb0000644000004100000410000000207111714455226023406 0ustar www-datawww-datarequire 'facets/math/approx_equal' module Math # Calculates the Gini Coefficient (a measure of inequality of a distribution # based on the area between the Lorenz curve and the uniform curve). # # http://en.wikipedia.org/wiki/Gini_coefficient # # This is a slightly cleaner way of calculating the Gini Coefficient then # the previous implementationj. # # GC = \frac{\sum_{i=1}^N (2i-N-1)x_i}{N^2-\bar{x}} # def self.gini_coefficient(array) return -1 if size <= 0 or any? { |x| x < 0 } return 0 if size < 2 or all? { |x| approx_equal(x,0) } s = 0 sort.each_with_index { |li,i| s += (2*i+1-size)*li } s.to_f/(size**2*mean).to_f end ## OLD WAY ## GC = \frac{1}{N} \left ( N+1-2\frac{\sum_{i=1}^N (N+1-i)y_i}{\sum_{i=1}^N y_i} \right ) ## def self.gini_coefficient2(array) ## return -1 if size <= 0 or any? { |x| x < 0 } ## return 0 if size < 2 or all? { |x| Math::float_equal(x,0) } ## s = 0 ## sort.each_with_index { |yi,i| s += (size - i)*yi } ## (size+1-2*(s.to_f/sum.to_f)).to_f/size.to_f ## end end facets-2.9.3/lib/standard/facets/math/pstd.rb0000644000004100000410000000003211714455226021067 0ustar www-datawww-datarequire 'facets/math/std' facets-2.9.3/lib/standard/facets/math/exp10.rb0000644000004100000410000000012211714455226021052 0ustar www-datawww-datamodule Math # 10 to the power +x+ def self.exp10(x) 10.0 ** x end end facets-2.9.3/lib/standard/facets/math/floor.rb0000644000004100000410000000014111714455226021237 0ustar www-datawww-datamodule Math # Largest integer not larger than +x+. def self.floor(x) x.floor end end facets-2.9.3/lib/standard/facets/math/sqsolve.rb0000644000004100000410000000565111714455226021625 0ustar www-datawww-datarequire 'facets/math/linsolve' module Math # Returns array of real solution of ax**2 + bx + c = d # or nil if no or an infinite number of solutions exist. # If +d+ is missing it is assumed to be 0. # # In order to solve ax**2 + bx + c = d +sqsolve+ identifies several cases: # * a == 0: # The equation to be solved is the linear equation bx + c = d. #sqsolve> delegates the computation to # #linsolve>. If it results in +nil+, +nil+ is returned (not [nil]!). Otherwise a one-element array # containing result of #linsolve is returned. # * a != 0: # The equation to be solved actually is a second order one. # * c == d # The equation to be solved is ax**2 + bx = 0. One solution of this equation obviously is # x = 0, the second one solves ax + b = 0. The solution of the latter is # delegated to +linsolve+. An array containing both results in ascending order is returned. # * c != d # The equation cannot be separated into x times some factor. # * b == 0 # The equation to be solved is ax**2 + c = d. This can be written as the linear equation # ay + c = d with y = x ** 2. The solution of the linear equation is delegated # to +linsolve+. If the returned value for +y+ is +nil+, that becomes the overall return value. # Otherwise an array containing the negative and positive squareroot of +y+ is returned # * b != 0 # The equation cannot be reduced to simpler cases. We now first have to compute what is called the # discriminant x = b**2 + 4a(d - c) (that's what we need to compute the square root of). # If the descriminant is negative no real solution exists and nil is returned. The ternary # operator checking whether b is negative does ensure better numerical stability --only one # of the two solutions is computed using the widely know formula for solving second order equations. # The second one is computed from the fact that the product of both solutions is (c - d) / a. # Take a look at a book on numerical mathematics if you don't understand why this should be done. # # @author Josef Schugt def self.sqsolve(a, b, c, d = 0.0) if a == 0.0 x = linsolve(b, c, d) return x.nil? ? nil: [ linsolve(b, c, d) ] else return [0.0, linsolve(a, b)].sort if c == d if b == 0.0 x = linsolve(a, c, d) x < 0.0 ? nil : [-Math.sqrt(x), Math.sqrt(x)] else x = b * b + 4.0 * a * (d - c) return nil if x < 0.0 x = b < 0 ? b - Math.sqrt(x) : b + Math.sqrt(x) [-0.5 * x / a, 2.0 * (d - c) / x].sort end end end end facets-2.9.3/lib/standard/facets/math/summed_sqdevs.rb0000644000004100000410000000040111714455226022774 0ustar www-datawww-datarequire 'facets/math/sum' require 'facets/math/mean' module Math # The sum of the squared deviations from the mean. # def self.summed_sqdevs(array) return 0 if array.size < 2 m = mean(array) sum(array.map{ |x| (x - m) ** 2 }) end end facets-2.9.3/lib/standard/facets/math/sum.rb0000644000004100000410000000044611714455226020732 0ustar www-datawww-datamodule Math # Returns sum. When a block is given, summation is taken over the # each result of block evaluation. # def self.sum(array) #:yield: sum = 0.0 if block_given? array.each{|i| sum += yield(i)} else array.each{|i| sum += i} end sum end end facets-2.9.3/lib/standard/facets/math/gcd.rb0000644000004100000410000000061411714455226020660 0ustar www-datawww-datamodule Math # Greatest common divisor of +m+ and +n+, +nil+ for non-positive # numbers - gcd is computed by means of the Euclidian algorithm. def self.gcd(m, n) m = Integer(m) n = Integer(n) if m <= 0 || n <= 0 return nil end loop { if m < n m, n = n, m end if (l = m % n) == 0 break end m = l } n end end facets-2.9.3/lib/standard/facets/math/acot.rb0000644000004100000410000000013711714455226021051 0ustar www-datawww-datamodule Math # Arcus cotangens of +x+ def self.acot(x) (PI * 0.5) - atan(x) end end facets-2.9.3/lib/standard/facets/math/sinc.rb0000644000004100000410000000014711714455226021060 0ustar www-datawww-datamodule Math # Sinc function of +x+. def self.sinc(x) (x == 0.0) ? 1.0 : sin(x) / x end end facets-2.9.3/lib/standard/facets/math/sqr.rb0000644000004100000410000000011211714455226020721 0ustar www-datawww-datamodule Math # Square of number. def self.sqr(x) x * x end end facets-2.9.3/lib/standard/facets/math/asec.rb0000644000004100000410000000012511714455226021033 0ustar www-datawww-datamodule Math # Arcus secans of +x+ def self.asec(x) acos(1.0 / x) end end facets-2.9.3/lib/standard/facets/math/tgamma.rb0000644000004100000410000000016111714455226021366 0ustar www-datawww-datarequire 'facets/math/lgamma' module Math # Exp of LGamma. def self.tgamma(x) exp(lgamma(x)) end end facets-2.9.3/lib/standard/facets/math/variance.rb0000644000004100000410000000123211714455226021710 0ustar www-datawww-datarequire 'facets/math/summed_sqdevs' module Math # def self.variance(array, &block) sum2 = if block_given? sum(array){ |i| j = block[i]; j*j } else sum(array){ |i| i**2 } end sum2/array.size - mean(array, &block)**2 end # Variance of the sample. # Variance of 0 or 1 elements is 0.0. # # TODO: Same as #variance? Then choose one. def self.variance2(array) return 0.0 if array.size < 2 summed_sqdevs(array) / (array.size - 1) end # Variance of a population. # Variance of 0 or 1 elements is 0.0. def self.pvariance(array) return 0.0 if array.size < 2 summed_sqdevs(array) / array.size end end facets-2.9.3/lib/standard/facets/math/ceil.rb0000644000004100000410000000014111714455226021032 0ustar www-datawww-datamodule Math # Smallest integer not smaller than +x+. def self.ceil(x) x.ceil end end facets-2.9.3/lib/standard/facets/math/kldivergence.rb0000644000004100000410000000077611714455226022576 0ustar www-datawww-datamodule Math # The Kullback-Leibler divergence from this array to that of +q+. # # NB: You will possibly want to sort both P and Q before calling this # depending on what you're actually trying to measure. # # http://en.wikipedia.org/wiki/Kullback-Leibler_divergence # def self.kldivergence(array, q) fail "Buggy." fail "Cannot compare differently sized arrays." unless size = q.size kld = 0 each_with_index { |pi,i| kld += pi*Math::log(pi.to_f/q[i].to_f) } kld end end facets-2.9.3/lib/standard/facets/math/lgamma.rb0000644000004100000410000000115411714455226021361 0ustar www-datawww-datamodule Math unless defined?(lgamma) # Logarithmus naturalis of gamma function of +x+. # # @author Josef Schugt def self.lgamma(x) h = x + 5.5 h -= (x + 0.5) * log(h) sum = 1.000_000_000_190_015 sum += 76.180_091_729_471_46 / (x + 1.0) sum -= 86.505_320_329_416_77 / (x + 2.0) sum += 24.014_098_240_830_91 / (x + 3.0) sum -= 1.231_739_572_450_155 / (x + 4.0) sum += 0.120_865_097_386_617_9e-2 / (x + 5.0) sum -= 0.539_523_938_495_3e-5 / (x + 6.0) -h + log(2.506_628_274_631_000_5 * sum / x) end end end facets-2.9.3/lib/standard/facets/math/cdf.rb0000644000004100000410000000040011714455226020650 0ustar www-datawww-datamodule Math # Returns the Cumulative Density Function of this # sample (normalised to a fraction of 1.0). def self.cdf(array, normalised=1.0) s = sum(array).to_f array.sort.inject([0.0]) { |c,d| c << c[-1] + normalised*d.to_f/s } end end facets-2.9.3/lib/standard/facets/math/epsilon.rb0000644000004100000410000000111411714455226021570 0ustar www-datawww-datamodule Math # Levi-Civita symbol of +i+, +j+, and +k+ - 1 if (+i+, +j+, +k+) # is (1, 2, 3), (2, 3, 1), or (3, 1, 2), -1 if it is (1, 3, 2), # (2, 1, 3), or (3, 2, 1), 0 as long as +i+, +j+, and +k+ are # all elements of {1, 2, 3}, otherwise returns nil. def self.epsilon(i, j, k) i = Integer(i) return nil if i < 1 or i > 3 j = Integer(j) return nil if j < 1 or j > 3 k = Integer(k) return nil if k < 1 or k > 3 case i * 16 + j * 4 + k when 27, 45, 54 then return 1 when 30, 39, 57 then return -1 end 0 end end facets-2.9.3/lib/standard/facets/math/gamma.rb0000644000004100000410000000021011714455226021175 0ustar www-datawww-datarequire 'facets/math/lgamma' module Math unless defined?(gamma) # def self.gamma(x) exp(lgamma(x)) end end end facets-2.9.3/lib/standard/facets/math/sech.rb0000644000004100000410000000013411714455226021042 0ustar www-datawww-datamodule Math # Secans hyperbolicus of +x+ def self.sech(x) 1.0 / cosh(x) end end facets-2.9.3/lib/standard/facets/math/amd.rb0000644000004100000410000000054711714455226020671 0ustar www-datawww-datarequire 'facets/math/rmd' require 'facets/math/mean' module Math # The average absolute difference of two independent values drawn # from the sample. Equal to the RMD * mean. def self.amd(array) rmd(array) * mean(array) end class << self alias_method :absolute_mean_difference, :amd #alias_method :md, :mean_difference end end facets-2.9.3/lib/standard/facets/math/acsc.rb0000644000004100000410000000012711714455226021033 0ustar www-datawww-datamodule Math # Arcus cosecans of +x+ def self.acsc(x) asin(1.0 / x) end end facets-2.9.3/lib/standard/facets/math/lcm.rb0000644000004100000410000000050411714455226020674 0ustar www-datawww-datamodule Math # Least common multiple of +m+ and +n+, computed by multiplying # +m+ and +n+ and dividing the product by the gcd of +m+ and +n+, # +nil+ for non-positive numbers. def self.lcm(m, n) m = Integer(m) n = Integer(n) if m <= 0 || n <= 0 return nil end m / gcd(m, n) * n end end facets-2.9.3/lib/standard/facets/math/delta.rb0000644000004100000410000000026511714455226021216 0ustar www-datawww-datamodule Math # Kronecker symbol of +i+ and +j+. # Returns 1 if +i+ and +j+ are equal, 0 otherwise. def self.delta(i, j) return Integer(i) == Integer(j) ? 1 : 0 end end facets-2.9.3/lib/standard/facets/math/stderr.rb0000644000004100000410000000003211714455226021420 0ustar www-datawww-datarequire 'facets/math/std' facets-2.9.3/lib/standard/facets/math/sign.rb0000644000004100000410000000026011714455226021060 0ustar www-datawww-datamodule Math # Sign of +x+. # Returns -1 for negative x, +1 for positive x and zero for x = 0 def self.sign(x) (x > 0.0) ? 1.0 : ((x < 0.0) ? -1.0 : 0.0) end end facets-2.9.3/lib/standard/facets/math/beta.rb0000644000004100000410000000031611714455226021035 0ustar www-datawww-datamodule Math # Beta function of +x+ and +y+ - beta(+x+, +y+) = # tgamma(+x+) * tgamma(+y+) / tgamma(+x+ + +y+) def self.beta(x, y) exp(lgamma(x) + lgamma(y) - lgamma(x+y)) end end facets-2.9.3/lib/standard/facets/math/asech.rb0000644000004100000410000000016211714455226021204 0ustar www-datawww-datamodule Math # Area secans hyperbolicus of +x+ def asech(x) log((1.0 + sqrt(1.0 - x * x)) / x) end end facets-2.9.3/lib/standard/facets/math/max.rb0000644000004100000410000000003211714455226020702 0ustar www-datawww-datarequire 'facets/math/min' facets-2.9.3/lib/standard/facets/math/factorial.rb0000644000004100000410000000106711714455226022072 0ustar www-datawww-datamodule Math # First 16 factorials. FACTORIALS = [ 1, 1, 2, 6, 24, 120, 720, 5_040, 40_320, 362_880, 3_628_800, 39_916_800, 479_001_600, 6_227_020_800, 87_178_291_200, 1_307_674_368_000 ] # 1 * 2 * ... * +n+, nil for negative numbers def self.factorial(n) n = Integer(n) if n < 0 nil elsif FACTORIALS.length > n FACTORIALS[n] else h = FACTORIALS.last (FACTORIALS.length .. n).each { |i| FACTORIALS.push h *= i } h end end end facets-2.9.3/lib/standard/facets/math/sec.rb0000644000004100000410000000011611714455226020672 0ustar www-datawww-datamodule Math # Secans of +x+. def self.sec(x) 1.0 / cos(x) end end facets-2.9.3/lib/standard/facets/math/linsolve.rb0000644000004100000410000000045211714455226021756 0ustar www-datawww-datamodule Math # Returns real solution(s) of +a+x + +b+ = +c+ or +nil+ # if no or an infinite number of solutions exist. If # c is missing it is assumed to be 0. # # @author Josef Schugt def self.linsolve(a, b, c = 0.0) a == 0 ? nil : (c - b) / a end end facets-2.9.3/lib/standard/facets/math/coth.rb0000644000004100000410000000013711714455226021060 0ustar www-datawww-datamodule Math # Cotangens hyperbolicus of +x+ def self.coth(x) 1.0 / tanh(x) end end facets-2.9.3/lib/standard/facets/math/approx_equal.rb0000644000004100000410000000035511714455226022625 0ustar www-datawww-datamodule Math # EPSILON = 0.000000001 # Approximately equal. # # TODO: Use core extension Numeric#approx? instead (?) def self.approx_equal(a, b, epsilon=EPSILON) c = a - b c *= -1.0 if c < 0 c < epsilon end end facets-2.9.3/lib/standard/facets/math/rmd.rb0000644000004100000410000000055511714455226020711 0ustar www-datawww-datarequire 'facets/math/approx_equal' module Math # Calculates the relative mean difference of this sample. # Makes use of the fact that the Gini Coefficient is half the RMD. def self.rmd(array) return 0.0 if approx_equal(mean(array), 0.0) gini_coefficient(array) * 2 end class << self alias_method :relative_mean_difference, :rmd end end facets-2.9.3/lib/standard/facets/math/acsch.rb0000644000004100000410000000020611714455226021201 0ustar www-datawww-datamodule Math # Area cosecans hyperbolicus of +x+ def acsch(x) ::Math.log(1.0 / x + Math.sqrt(1.0 + 1.0 / (x * x))) end end facets-2.9.3/lib/standard/facets/math/acoth.rb0000644000004100000410000000017011714455226021216 0ustar www-datawww-datamodule Math # Area cotangens hyperbolicus of +x+ def self.acoth(x) 0.5 * log((x + 1.0) / (x - 1.0)) end end facets-2.9.3/lib/standard/facets/math/mean.rb0000644000004100000410000000034511714455226021044 0ustar www-datawww-datarequire 'facets/math/sum' module Math # Mean average. def self.mean(array, &blk) s = array.size return 0.0 if s == 0 sum(array, &blk) / s end class << self alias_method :mean_average, :mean end end facets-2.9.3/lib/standard/facets/math/root.rb0000644000004100000410000000013211714455226021101 0ustar www-datawww-datamodule Math # The +y+ root of +x+. def self.root(x, y) x ** (1.0 / y) end end facets-2.9.3/lib/standard/facets/math/csch.rb0000644000004100000410000000013611714455226021042 0ustar www-datawww-datamodule Math # Cosecans hyperbolicus of +x+ def self.csch(x) 1.0 / sinh(x) end end facets-2.9.3/lib/standard/facets/math/pow.rb0000644000004100000410000000012111714455226020721 0ustar www-datawww-datamodule Math # +x+ to the power +y+ def self.pow(x, y) x ** y end end facets-2.9.3/lib/standard/facets/math/atkinson_index.rb0000644000004100000410000000047711714455226023147 0ustar www-datawww-datarequire 'facets/math/theil_index' module Math # Closely related to the Theil index and easily expressible # in terms of it. # # AI = 1-e^{theil_index} # # http://en.wikipedia.org/wiki/Atkinson_index def self.atkinson_index(array) t = theil_index(array) (t < 0) ? -1 : 1-Math::E**(-t) end end facets-2.9.3/lib/standard/facets/math/exp2.rb0000644000004100000410000000011711714455226020777 0ustar www-datawww-datamodule Math # 2 to the power +x+ def self.exp2(x) 2.0 ** x end end facets-2.9.3/lib/standard/facets/math/theil_index.rb0000644000004100000410000000116311714455226022417 0ustar www-datawww-datarequire 'facets/math/sum' require 'facets/math/mean' require 'facets/math/approx_equal' module Math # Calculates the Theil index (a statistic used to measure # economic inequality). # # TI = \sum_{i=1}^N \frac{x_i}{\sum_{j=1}^N x_j} ln \frac{x_i}{\bar{x}} # # http://en.wikipedia.org/wiki/Theil_index # def self.theil_index(array) return -1 if array.size <= 0 or any? { |x| x < 0 } return 0 if array.size < 2 or all? { |x| approx_equal(x, 0) } m = mean(array) s = sum(array).to_f inject(0) do |theil, xi| theil + ((xi > 0) ? (log(xi.to_f/m) * xi.to_f/s) : 0.0) end end end facets-2.9.3/lib/standard/facets/math/log2.rb0000644000004100000410000000027111714455226020765 0ustar www-datawww-datamodule Math INVERSE_LN_2 = 1.0 / ::Math.log(2.0) unless defined?(log2) # Logarithmus dualis of +x+. def self.log2(x) Math.log(x) * INVERSE_LN_2 end end end facets-2.9.3/lib/standard/facets/math/pvariance.rb0000644000004100000410000000003711714455226022072 0ustar www-datawww-datarequire 'facets/math/variance' facets-2.9.3/lib/standard/facets/math/percentile.rb0000644000004100000410000000167611714455226022266 0ustar www-datawww-datamodule Math # Returns the percentile value for percentile _pcnt_; nil if array is empty. # # +pcnt+ should be expressed as an integer, e.g. `percentile(90)` returns # the 90th percentile of the array. # # Algorithm from NIST[http://www.itl.nist.gov/div898/handbook/prc/section2/prc252.htm] # # NOTE: This is not a common core extension and is not # loaded automatically when using require 'facets'. # # CREDIT: Ben Koski # # @non-core # require 'facets/array/precentile' # def self.percentile(array, pcnt) sorted_array = array.sort return nil if array.length == 0 rank = (pcnt.to_f / 100) * (array.length + 1) whole = rank.truncate # if has fractional part if whole != rank s0 = sorted_array[whole - 1] s1 = sorted_array[whole] f = (rank - rank.truncate).abs return (f * (s1 - s0)) + s0 else return sorted_array[whole - 1] end end end facets-2.9.3/lib/standard/facets/math/abs.rb0000644000004100000410000000011711714455226020666 0ustar www-datawww-datamodule Math # Absolute value of +x+. def self.abs(x) x.abs end end facets-2.9.3/lib/standard/facets/math.rb0000644000004100000410000000311511714455226020122 0ustar www-datawww-datareqiure 'facets/kernel/require_relative' require_relative 'abs.rb' require_relative 'acot.rb' require_relative 'acoth.rb' require_relative 'acsc.rb' require_relative 'acsch.rb' require_relative 'amd.rb' require_relative 'approx_equal.rb' require_relative 'asec.rb' require_relative 'asech.rb' require_relative 'atkinson_index.rb' require_relative 'beta.rb' require_relative 'cdf.rb' require_relative 'ceil.rb' require_relative 'cot.rb' require_relative 'coth.rb' require_relative 'csc.rb' require_relative 'csch.rb' require_relative 'delta.rb' require_relative 'epsilon.rb' require_relative 'exp2.rb' require_relative 'exp10.rb' require_relative 'factorial.rb' require_relative 'floor.rb' require_relative 'gamma.rb' require_relative 'gcd.rb' require_relative 'gini_coefficient.rb' require_relative 'kldivergence.rb' require_relative 'lcm.rb' require_relative 'lgamma.rb' require_relative 'linsolve.rb' require_relative 'log2.rb' require_relative 'max.rb' require_relative 'mean.rb' require_relative 'median.rb' require_relative 'min.rb' require_relative 'percentile.rb' require_relative 'pow.rb' require_relative 'pstd.rb' require_relative 'pvariance.rb' require_relative 'rmd.rb' require_relative 'root.rb' require_relative 'round.rb' require_relative 'sec.rb' require_relative 'sech.rb' require_relative 'sign.rb' require_relative 'sinc.rb' require_relative 'sqr.rb' require_relative 'sqsolve.rb' require_relative 'std.rb' require_relative 'stderr.rb' require_relative 'sum.rb' require_relative 'summed_sqdevs.rb' require_relative 'tgamma.rb' require_relative 'theil_index.rb' require_relative 'variance.rb' facets-2.9.3/lib/standard/facets/enumargs.rb0000644000004100000410000001033111714455226021010 0ustar www-datawww-data# Enumerable::Arguments # # Copyright (c) 2004 Thomas Sawyer # # LGPL(3) License # # This module is free software. You may use, modify, and/or redistribute this # software under the same terms as Ruby. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. begin require 'enumerator' rescue LoadError end # This is a simple reimplementation of the core Enumerable module # to allow the methods to take and pass-on arbitrary arguments to the # underlying #each call. This library uses Enumerator and scans # Enumerable so it can alwasy stay in sync. # # NOTE Any Enumerable method with a negative arity cannot do pass arguments # due to ambiguity in the argument count. So the methods #inject and #zip # do NOT work this way, but simply work as they do in Enumerable. # The method #find (and #detect) though has been made to work by removing # its rarely used optional parameter and providing instead an optional # keyword parameter (:ifnone => ...). Please keep these difference in mind. # # require 'enumargs' # # class T # include Enumerable::Arguments # def initialize(arr) # @arr = arr # end # def each(n) # arr.each{ |e| yield(e+n) } # end # end # # t = T.new([1,2,3]) # t.collect(4) # #=> [5,6,7] # module Enumerable module Arguments def self.wrap_enumerable_method( methodname ) m = methodname meth = Enumerable.instance_method(m) arity = meth.arity case arity <=> 0 when 0 class_eval %{ def #{m}( *args, &yld ) enum_for(:each, *args).#{m}( &yld ) end } when 1 class_eval %{ def #{m}( *args, &yld ) args, each_args = args[0...#{arity}], args[#{arity}..-1] enum_for(:each, *each_args).#{m}( *args, &yld ) end } else class_eval %{ def #{m}( *args, &yld ) enum_for(:each).#{m}( *args, &yld ) end } end end Enumerable.instance_methods(false).each do |m| wrap_enumerable_method( m ) end # def to_a(*args) map(*args){ |x| x } end # Make exception for #find (a negative arity method) to accept # keyword argument. # # ObjectSpace.find(Class, :ifnone=>lambda{1}) { |e| ... } # ObjectSpace.find(Class, :ifnone=>lambda{1}) { |e| ... } # def find(*args, &yld) # future use **keys ? if Hash === args.last and args.last.key?(:ifnone) ifnone = args.last.delete(:ifnone) args.pop if args.last.empty? enum_for(:each, *args).find( ifnone, &yld ) else enum_for(:each, *args).find( &yld ) end end alias_method :detect, :find end end =begin OLD CODE module EnumerableArgs def collect(*args) # :yield: a = [] each(*args){ |n| a << yield(n) } a end alias_method( :map, :collect ) def detect(*args) # :yield: each(*args){ |n| return n if yield(n) } nil end alias_method( :find, :detect ) def each_with_index(*args) i=0 each(*args){ |*n| n << i; yield(*n); i+=1 } self end def to_a(*args) a = [] each(*args){ |n| a << n } a end alias_method( :entries, :to_a ) # An additional method not part of standard Enumerable. # The regular version of this method can be found in Facets, # but it is a bit more advanced then this one. # At some point they need to be put into sync. def each_slice(*args, &yld) a = []; s = [] ar = yld.arity.abs each(*args){ |n| s << n if s.length >= ar yld.call(*s) s = [] end } a end alias_method( :each_by, :each_slice ) def select(*args) # :yield: a = [] each(*args){ |n| a << n if yield(n) } a end alias_method( :find_all, :select ) def grep(pattern, *args) a = [] each(*args){ |n| a << (block_given? ? yield(n) : n) if pattern === n } a end def include?(anObj, *args) each(*args){ |n| return true if anObj == n } false end alias_method( :member?, :include? ) def max(*args) to_a(*args).max end def min(*args) to_a(*args).min end def reject(*args) a = [] each(*args){ |n| a << n if ! yield(n) } a end def sort(*args) # TODO end end =end facets-2.9.3/lib/standard/facets/uri.rb0000644000004100000410000001152211714455226017771 0ustar www-datawww-datarequire 'uri' #require 'cgi' require 'facets/kernel/blank' module URI module_function # Decode the uri components. # def decode(uri) ## gmosx: hmm is this needed? ## guard against invalid filenames for example pictures with ## spaces uploaded by users escaped_uri = uri.gsub(/ /, "+") if md = URI::REGEXP::REL_URI.match(escaped_uri) path = "#{md[5]}#{md[6]}" type = File.extname(path) query_string = md[7] ## real_path = "#{$root_dir}/#{path}" parameters = URI.query_to_hash(query_string) path.gsub!(/\+/, " ") return [path, type, parameters, query_string] end ## this is usefull for uncovering bugs! raise ArgumentError.new("the parameter '#{uri}' is not a valid uri") end # Extend the basic query string parser provided by the cgi module. # converts single valued params (the most common case) to # objects instead of arrays # # Returns hash of parameters, contains arrays for multivalued parameters # (multiselect, checkboxes , etc). # # If no query string is provided (nil or "") returns an empty hash. def query_to_hash(query_string) return {} unless query_string query_parameters = cgi_parse(query_string) query_parameters.each { |key, val| ## replace the array with an object query_parameters[key] = val[0] if 1 == val.length } ## set default value to nil! cgi sets this to [] query_parameters.default = nil return query_parameters end alias_method :query_string_to_hash, :query_to_hash # KEY_VALUE_SEPARATOR = ";" # "&" # Given a hash with parameter/value pairs construct a # standard query string. # # URI.hash_to_query(:a => 1, :b => 2) # #=> "a=1;b=2" # def hash_to_query(parameters) return '' unless parameters pairs = [] parameters.each do |param, value| pairs << "#{param}=#{cgi_escape(value.to_s)}" end return pairs.join(KEY_VALUE_SEPARATOR) end alias_method :hash_to_query_string, :hash_to_query # CGI escape # # TODO: How does this compare to URI.escape? def cgi_escape(string) string.gsub(/([^ a-zA-Z0-9_.-]+)/n) do '%' + $1.unpack('H2' * $1.size).join('%').upcase end.tr(' ', '+') end # def cgi_unescape(string) string.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n) do [$1.delete('%')].pack('H*') end end # def cgi_parse(query) params = Hash.new([].freeze) query.split(/[&;]/n).each do |pairs| key, value = pairs.split('=',2).collect{|v| cgi_unescape(v) } if params.has_key?(key) params[key].push(value) else params[key] = [value] end end params end # This method returns the query string of a uri # # Input: # the uri # # Output: # the query string. # returns nil if no query string def get_query_string(uri) return nil unless uri # gmosx: INVESTIGATE ruby's URI seems to differently handle # abs and rel uris. if md = URI::REGEXP::ABS_URI.match(uri) return md[8] elsif md = URI::REGEXP::REL_URI.match(uri) return md[7] end return nil end # Removes the query string from a +uri+. # # Returns the chomped uri. def chomp_query_string(uri) return nil unless uri query_string = self.get_query_string(uri) return uri.dup.chomp("?#{query_string}") end # Get a uri and a hash of parameters. Inject the hash values # as parameters in the query sting path. Returns the full uri. # # uri - the uri to filter (String) # parameter - hash of parameters to update # # Returns the full updated query string. # # TODO: optimize def update_query_string(uri, parameters) query_string = self.get_query_string(uri) rest = uri.dup.gsub(/\?#{query_string}/, "") hash = self.query_string_to_hash(query_string) hash.update(parameters) query_string = self.hash_to_query_string(hash) unless query_string.blank? return "#{rest}?#{query_string}" else return rest end end # Gets the request uri, injects extra parameters in the query string # and returns a new uri. The request object is not modified. # There is always a qs string so an extra test is skipped. # # TODO: find a better name? def update_request_uri(request, parameters) hash = request.parameters.dup() hash.update(parameters) ## use this in hash_to_querystring. query_string = hash.collect { |k, v| "#{k}=#{v}" }.join(";") ## return "#{request.translated_uri}?#{query_string}" return "#{request.path}?#{query_string}" end module Kernel # def uri(s, w=%r{[^a-zA-Z_0-9./-]}) URI.escape(s, w) end # def unuri(s) URI.unescape(s) end end module Hash # def to_uri URI.hash_to_query(self) end end end class Object #:nodoc: include URI::Kernel end class Hash #:nodoc: include URI::Hash end facets-2.9.3/lib/standard/facets/nullclass.rb0000644000004100000410000000130311714455226021166 0ustar www-datawww-data# = Nullclass # # NullClass is essentially NilClass but it differs in one # important way. When a method is called against it that it # deoesn't have, it will simply return null value rather then # raise an error. # # TODO: Perhaps NullClass should be called NackClass? class NullClass #< NilClass class << self def new @null ||= NullClass.allocate end end def inspect ; 'null' ; end def nil? ; true ; end def null? ; true ; end def [](key); nil; end def method_missing(sym, *args) return nil if sym.to_s[-1,1] == '?' self end end module Kernel def null NullClass.new end end class Object def null? false end end # Copyright (c) 2005 Thomas Sawyer facets-2.9.3/lib/standard/facets/cgi.rb0000644000004100000410000000251011714455226017731 0ustar www-datawww-datarequire 'cgi' class CGI # Create an hidden input field through which an object can can be marshalled. # This makes it very easy to pass from data betwenn requests. def marshal_to_cgi(name, iobj) data = CGI.escape(Marshal.dump(iobj)) return %Q{\n} end # Create an hidden input field through which an object can can be marshalled. # This makes it very easy to pass from data between requests. def marshal_from_cgi(name) if self.params.has_key?("__#{name}__") return Marshal.load(CGI.unescape(self["__#{name}__"][0])) end end # TODO: Rename CGI#esc ? # TODO: Are these two good enough to replace CGI.escape? # Return an html "safe" version of the string, # where every &, < and > are replaced with appropriate entities. def esc(str) str.gsub(/&/,'&').gsub(//,'>') end # Calls #esc, and then further replaces carriage returns and quote characters with entities. def escformat(str) esc(str).gsub(/[\r\n]+/,' ').gsub(%r|"|,'"').gsub(%r|'|,''') end class << self alias :escape_html :escapeHTML alias :unescape_html :unescapeHTML alias :escape_element :escapeElement alias :unescape_element :unescapeElement end end # Copyright (c) 2005 Thomas Sawyer (Ruby License) facets-2.9.3/lib/standard/facets/instantiable.rb0000644000004100000410000000066711714455226021657 0ustar www-datawww-data# = Instantiable # # Initialize modules, almost as if they were classes. # # Alows a module to be used much like a class, by defining # a #new method that creates a class on demand. # module Instantiable def self.append_features(mod) mod.extend self end # Never use a class again! ;) def new(*args,&blk) mod = self @instantiable_class ||= Class.new{include mod} @instantiable_class.new(*args,&blk) end end facets-2.9.3/lib/standard/facets/erb.rb0000644000004100000410000000260411714455226017743 0ustar www-datawww-datarequire 'erb' # = OpenTemplate # # The Erb OpenTemplate provides a quick and convenient way to # create a clean rendering space with the desired responses. # # Ruby 1.8.6 or less can't handle object scope methods with blocks. # # TODO: This might make a good addon library. Just add # require 'erb' to the erb_result method? Call it OpenResponse? # class ERB::OpenTemplate # TODO: Should we do this? Perhaps offer it as an option? instance_methods.each do |m| undef_method(m) unless /^(__|instance_|inspect$|extend$|object_id$)/ =~ m.to_s end # def initialize(*objs_ioc) ioc = Hash===objs_ioc.last ? objs_ioc.pop : {} objs = objs_ioc mods = [] objs.each do |obj| mod = Module.new obj.public_methods.each do |m| mod.module_eval do #define_method(m){ |*a,&b| obj.__send__(m,*a,&b) } define_method(m, &obj.method(m).to_proc) end end mods << mod end mod = Module.new ioc.each do |k,v| mod.module_eval do define_method(k){ v } end end mods << mod extend *mods.reverse end # def erb_result(str) ERB.new(str).result(binding) end ## ##def method_missing(sym, *args, &block) ## #if @ioc.key?(sym) ## # @ioc[sym] ## if obj = @objs.find{ |o| o.respond_to?(sym) } ## obj.__send__(sym, *args, &block) ## else ## super ## end ##end end facets-2.9.3/lib/standard/facets/opesc.rb0000644000004100000410000000373411714455226020311 0ustar www-datawww-data# = OpEsc # # NOTE: As of v3.0 of Facets these have been renamed: # # op_plus_self -> op_plus # op_minus_self -> op_minus # op_plus -> op_add # op_minus -> op_sub # op_case_eq -> op_case # # TODO: In the future we might also rename: # # op_lshift -> op_push # op_rshift -> op_pull # op_store -> op_index # op_fetch -> op_index (b/c [] and []= in same file) module OpEsc OPERATORS = %w{ +@ -@ + - ** * / % ~ <=> << >> < > === == =~ <= >= | & ^ []= [] } OPERATORS_REGEXP = Regexp.new( '(' << OPERATORS.collect{ |k| Regexp.escape(k) }.join('|') << ')' ) OPERATORS_ESC_TABLE = { "+@" => "op_plus", "-@" => "op_minus", "+" => "op_add", "-" => "op_sub", "**" => "op_pow", "*" => "op_mul", "/" => "op_div", "%" => "op_mod", "~" => "op_tilde", "<=>" => "op_cmp", "<<" => "op_lshift", #push? ">>" => "op_rshift", #pull? "<" => "op_lt", ">" => "op_gt", "===" => "op_case", "==" => "op_equal", "=~" => "op_apply", "<=" => "op_lt_eq", ">=" => "op_gt_eq", "|" => "op_or", "&" => "op_and", "^" => "op_xor", "[]=" => "op_store", "[]" => "op_fetch" } # Applies operator escape's according to OPERATORS_ESCAPE_TABLE. # # OpEsc.escape('-') #=> "op_sub" # # CREDIT: Trans def self.escape(str) str.to_s.gsub(OPERATORS_REGEXP){ OPERATORS_ESC_TABLE[$1] } end # def self.method_to_filename(name) fname = escape(name) fname = fname[0...-1] if fname =~ /[\!\=\?]$/ fname end ## Require a file with puncuation marks escaped. ## ## require_esc '[].rb' ## ## in actuality requires the file 'op_fetch.rb'. ## ## def require_esc( fpath ) ## fdir, fname = File.split(fpath) ## fname = method_to_filename(fname) ## path = File.join(fdir, fname) ## require(path) ## end end facets-2.9.3/lib/standard/facets/net/0000755000004100000410000000000011714455226017432 5ustar www-datawww-datafacets-2.9.3/lib/standard/facets/net/http.rb0000644000004100000410000000202611714455226020736 0ustar www-datawww-datarequire 'net/http' module Net # CREDIT: Daniel Huckstep def self.download(url, limit=10) raise ArgumentError, 'HTTP redirect too deep' if limit == 0 #url = URI.parse(url) #req = Net::HTTP::Get.new(url.path) #req['User-Agent'] = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.7) Gecko/2009030422 Ubuntu/8.10 (intrepid) Firefox/3.0.7" #resp = Net::HTTP.new(url.host, url.port).start { |http| http.request(req) } resp = Net::HTTP.get_response(URI.parse(url)) case resp when Net::HTTPSuccess then resp when Net::HTTPRedirection then download(resp['location'], limit - 1) else resp.error! end end # CREDIT: Daniel Huckstep def self.download_and_save(url, path=nil) if path.nil? path = File.expand_path(url.split('/').last) else path = File.expand_path(path) end raise ArgumentError.new('Save path is a directory') if File.directory?(path) resp = download(url) open(path,'w') { |file| file.write(resp.body) } if resp.is_a?(Net::HTTPSuccess) end end facets-2.9.3/lib/standard/facets/basicobject.rb0000644000004100000410000000442111714455226021442 0ustar www-datawww-data# Facets' BasicObject is an implementation of Jim Weirich's BlankSlate. # # BlankSlate # Copyright 2004 by Jim Weirich (jim@weirichhouse.org). # All rights reserved. # # Since Ruby 1.9 has a BasicObject class this will of course be # deprecated as 1.9 goes mainstream. unless defined? BasicObject # in case it already exists! # BasicObject provides an abstract base class with no predefined # methods (except for \_\_send__ and \_\_id__). # BlankSlate is useful as a base class when writing classes that # depend upon method_missing (e.g. dynamic proxies). class BasicObject class << self # Hide the method named +name+ in the BlankSlate class. Don't # hide +instance_eval+ or any method beginning with "__". # # According to 1.9.1 it should have only these methods: # # * #__send__ # * #instance_eval # * #instance_exec # * #equal? # * #== # * #! # * #!= # * respond_to? # # Seems to me it should have #__id__ too. def hide(name) undef_method name if instance_methods.include?(name.to_s) and name !~ /^(__|respond_to\?|instance_eval$|instance_exec$|equal\?$|\=\=$)/ end end instance_methods.each{ |m| hide(m) } end # Since Ruby is very dynamic, methods added to the ancestors of # BlankSlate after BlankSlate is defined will show up in the # list of available BlankSlate methods. We handle this by defining a # hook in the Object and Kernel classes that will hide any defined module Kernel #:nodoc: class << self alias_method :facets_basic_object_method_added, :method_added # Detect method additions to Kernel and remove them in the # BlankSlate class. def method_added(name) facets_basic_object_method_added(name) return if self != Kernel BasicObject.hide(name) end end end class Object #:nodoc: class << self alias_method :facets_basic_object_method_added, :method_added # Detect method additions to Object and remove them in the # BlankSlate class. def method_added(name) facets_basic_object_method_added(name) return if self != Object BasicObject.hide(name) end end end end facets-2.9.3/lib/standard/facets/strscan.rb0000644000004100000410000000067611714455226020657 0ustar www-datawww-datarequire 'strscan' class StringScanner # scans string until +pattern+ is encountered. If +pattern+ will not be # encountered then it returns _nil_ but if +scan_anyway+ is _true_ then # it scans until the end of the string. def scan_before(pattern, scan_anyway = false) if not check_until(pattern) and not scan_anyway then return nil; end result = "" result << getch until check(pattern) or eos? return result end end facets-2.9.3/lib/standard/facets/cloneable.rb0000644000004100000410000000332211714455226021115 0ustar www-datawww-data# Clonable provides a standard basis for adding deep cloneablity to a class # via the standard #dup and #clone methods. # # Cloneable was originally ported from Jim Weirich's Rake. # The current version is the work of Ken Bloom. # # CREDIT: Ken Bloom module Cloneable def initialize_copy(sibling) #first duplicate my superclass' state. Note that if it's duplicating #instance variables, this will be overwritten, but this is important #because we could be dealing with a C extension with state hidden from #the Ruby interpreter super #we want to know if we're being dup'ed or clone'd, because we want to #preserve the state of our internals the same way our state is being #preserved. (If we can't figure it out, we'll just use #dup.) operation = ( copy_call = caller.find{|x| x !~ /'initialize_copy'/} copy_match = copy_call.match(/`(dup|clone)'/) copy_match ? copy_match[1] : :dup ) sibling.instance_variables.each do |ivar| value = sibling.instance_variable_get(ivar) #set my instance variable to be a #dup or #clone #or my sibling, depending on what's happening to me right now instance_variable_set(ivar, value.send(operation)) end end # TODO: Is there a more robust means of determining if clone or dup is used? #def clone # @_copy_operation = :clone # super #end # #def dup # @_copy_operation = :dup # super #end end # OLD VERSION #module Cloneable # def clone # sibling = self.class.new # instance_variables.each do |ivar| # value = self.instance_variable_get(ivar) # sibling.instance_variable_set(ivar, value.dup) #rake_dup) # end # sibling # end # alias_method :dup, :clone #end facets-2.9.3/lib/standard/facets/getoptlong.rb0000644000004100000410000000170511714455226021356 0ustar www-datawww-datarequire 'getoptlong' # = GetoptLong # # Ruby's standard GetoptLong class with an added DSL. # # opts = GetoptLong.new do # reqs '--expect', '-x' # flag '--help', '-h' # end # # See GetoptLong::DSL for details. class GetoptLong alias :init :initialize # def initialize(*arguments, &block) if block_given? raise ArgumentError unless arguments.empty? arguments = DSL.new(&block).arguments end init(*arguments) end # DSL-mode parser. class DSL attr :arguments def initialize(&block) @arguments = [] instance_eval(&block) end # def flag(*opts) @arguments << (opts << GetoptLong::NO_ARGUMENT) end # def required(*opts) @arguments << (opts << GetoptLong::REQUIRED_ARGUMENT) end # alias :reqs :required # def optional(*opts) @arguments << (opts << GetoptLong::OPTIONAL_ARGUMENT) end # alias :opts :optional end end facets-2.9.3/lib/standard/facets/equitable.rb0000644000004100000410000000276511714455226021156 0ustar www-datawww-data# = Equitable # # This mixin provides methods of equality based # on a single #identity method which must return # a list of accessors used as the identity keys. # # It also provides a "shortcut" for creating the # #identity method based on given accessors and returns # the Equitable module for inclusion. # # include Equitable(:a, :b) # # is equivalent to including a module containing: # # def ==(other) # self.a == other.a && self.b == other.b # end # # def eql?(other) # self.a.eql?(other.a) && self.b.eql?(other.b) # end # # def hash() # self.a.hash ^ self.b.hash # end # module Equitable def self.identify(base, *accessors) base.send(:define_method, :identity){ accessors } self end def ==(o) identity.all?{ |a| send(a) == o.send(a) } end def eql?(o) identity.all?{ |a| send(a).eql?(o.send(a)) } end def hash identity.inject(0){ |memo, a| memo ^ send(a).hash } end end class Module # This function provided a "shortcut" for creating the # #identity method based on given accessors and returns # the Equitable module for inclusion. # # include Equitable(:a, :b) # # is equivalent to including a module containing: # # def ==(other) # self.a == other.a && self.b == other.b # end # # def eql?(other) # self.a.eql?(other.a) && self.b.eql?(other.b) # end # # def hash() # self.a.hash ^ self.b.hash # end # def Equitable(*accessors) Equitable.identify(self, *accessors) end end facets-2.9.3/lib/standard/facets/timer.rb0000644000004100000410000000734311714455226020320 0ustar www-datawww-datarequire 'timeout' # for TimeoutError # = Timer # # Provides a strightforward means for controlling time critical execution. # Can be used as a "stop watch" timer or as a "time bomb" timer: # # t = Timer.new(10) { raise TimeoutError, "timeout!" } # t.start # : # done within 10sec timeout # t.stop # t.start # : # if condition then # t.reset #--> restart timer # end # # A class method is also provided for easily timing the exectuion of a block. # # Timer.time do |timer| # timer.total_time.round #=> 0 # # sleep 1 # timer.total_time.round #=> 1 # # timer.stop # timer.total_time.round #=> 1 # # sleep 1 # timer.total_time.round #=> 1 # # timer.start # timer.total_time.round #=> 1 # # sleep 1 # timer.total_time.round #=> 2 # end # # Thanks to Paul Brannan for TimeLimit and Minero Aoki for Timer. # These two libraries served as models for building this class. class Timer # def initialize(time_limit=nil, &block) # standard timer @start_time = nil @end_time = nil @total_time = 0 @runnning = nil # for using time limit @time_limit = time_limit @on_timeout = block @current_thread = nil @timer_thread = nil end # attr_accessor :time_limit # def start_time @start_time end # def end_time @end_time end # def on_timeout( &block ) if block then @on_timeout = block true else false end end # Start the timer. def start @running = true @start_time = Time.now limit if @time_limit self ##if block_given? then ## begin ## yield( self ) ## ensure ## stop ## end ##else ## @time_limit ##end end # Establish a time limit on execution. def limit( time_limit=nil ) if @time_limit || time_limit @current_thread = Thread.current @timer_thread = Thread.fork { sleep @time_limit if @on_timeout then @on_timeout.call @time_limit else @current_thread.raise TimeoutError, "#{@time_limit} seconds past" end } end end # Kill time limit thread, if any. def defuse if @timer_thread #Thread.kill @timer_thread @timer_thread.kill @timer_thread = nil end end # Stops timer and returns total time. # If timer was not running returns false. def stop if @running defuse # record running time @end_time = Time.now @running = false @total_time += (@end_time - @start_time) else nil end end # Stops and resets the timer. If the timer was running # returns the total time. If not returns 0. def reset if running? r = stop else r = 0 end @total_time = 0 return r end # Resets the time limit. Same as: # # t.stop # t.start # def reset_limit #stop #start defuse limit end # Queries whether the timer is still running. def running? return @running end # Queries whether the timer is still not running. def stopped? return !@running end # Queries total recorded time of timer. def total_time if running? then return @total_time + (Time.now - @start_time) else return @total_time end end # Takes a block and returns the total time it took to execute. def self.time yield( timer = Timer.new.start ) return timer.total_time end # Timer::Dummy - Dummy Timer (i.e. no real time limit) #-- # TODO: Timer::Dummy needs some work. #++ class Dummy < self def start if block_given? then yield else time_limit() end end def stop false end end #class Dummy end #class Timer # Copyright (c) 2004 Rubyworks facets-2.9.3/lib/standard/facets/memoizable.rb0000644000004100000410000000723211714455226021321 0ustar www-datawww-data# Memoization is an optimization technique used primarily to speed up # programs by having function calls avoid repeating the calculation # of results for previously-processed inputs. # # When you "memoize" a method/function using Memoizable its results are cached # so that later calls return results from the cache instead of recalculating # them. # # class T # include Memoizable # # def initialize(a) # @a = a # end # # def a # "#{@a ^ 3 + 4}" # end # # memoize :a # end # # t = T.new(10) # (t.a.__id__ == t.a.__id__) #=> true # # This method can also be used at the instance level to cache singleton # (qua class) methods by including it in the singleton class. # #-- # TODO: It would be very cool if Memoizable could set-up default parameters # via #[] method, e.g. `include Memoizable[:freeze=>true]`. #++ module Memoizable @cache = Hash.new{|h,k|h[k]=Hash.new{|h,k|h[k]={}}} # def self.cache @cache end # def self.append_features(base) Module == base ? super(base) : base.extend(self) end # Directive for making your functions faster by trading space for time. # When you "memoize" a method/function using #memoize its results are # cached so that later calls with the same arguments return results from # the cache instead of recalculating them. # # The #memoize method also handles a few options to alter # behavior of the memoization: # # :class => true cache per-class not per-object # :freeze => true freeze the memoized return values # :arguments => false do not index cache by arguments # def memoize(*method_names) options = Hash === method_names.last ? method_names.pop : {} options[:arguments] = true if options[:arguments].nil? # default to true ref = options[:class] ? 'self.class.name' : 'self' frz = options[:freeze] ? '.freeze' : '' arg = options[:arguments] ? '[__a__, block_given?]' : 'nil' code = "" method_names.each do |m| code << <<-code alias_method '#{ m }:memo', '#{ m }' private '#{ m }:memo' def #{ m }(*__a__,&__b__) c = Memoizable.cache[#{ref}][:'#{ m }'] k = #{arg} if c.has_key?(k) c[k] else c[k] = __send__('#{ m }:memo',*__a__,&__b__)#{frz} end end code end module_eval(code) end # Remove the memoized value from the memoization cache. # The next time a memoized methos is called if will be # remomoized. def rememoize(*method_names) if Memoizable.cache[self] if method_names.empty? Memoizable.cache.delete(self) else method_names.each do |m| Memoizable.cache[self].delete(m.to_sym) end end end if Memoizable.cache[self.class.name] if method_names.empty? Memoizable.cache.delete(self.class.name) else method_names.each do |m| Memoizable.cache[self.class.name].delete(m.to_sym) end end end end # def unmemoize(*method_names) rememoize(*method_names) method_names.each do |m| alias_method name, "#{ m }:memo" end end # Include Memoizable alone with an #initialize_copy method that # will copy the memoization cache when #dup or #clone is used. # # TODO: Is this best approach? Perhaps a method to easily create # the #initialize_copy method would suffice? module Copy # def self.included(base) base.extend(Memoizable) end # def initialize_copy(original) if Memoizable.cache.key?(original) Memoizable.cache[self] = Memoizable.cache[original].dup end end end end facets-2.9.3/lib/standard/facets/ostruct.rb0000644000004100000410000001106211714455226020674 0ustar www-datawww-datarequire 'ostruct' class OpenStruct # Allows the initialization of an OpenStruct with a setter block: # # person = OpenStruct.new do |o| # o.name = 'John Smith' # o.gender = :M # o.age = 71 # end # # You can still provide a hash for initialization purposes, and even combine # the two approaches if you wish. # # person = OpenStruct.new(:name => 'John Smith', :age => 31) do |p| # p.gender = :M # end # # Alternatively you can provide a default block: # # stuff = OpenStruct.new{ |o,k| o[k] = [] } # stuff.place << :a # stuff.place << :b # stuff.place #=> [:a, :b] # # A setter block versus a defualt block is determined by the arity of # the block. You can not provide both at the same time. # # CREDIT: Noah Gibbs, Gavin Sinclair def initialize(hash=nil, &block) if block && block.arity==2 @table = Hash.new(&block) else @table = {} end if hash for k,v in hash @table[k.to_sym] = v new_ostruct_member(k) end end if block && block.arity==1 yield self end end # def each(&blk) @table.each(&blk) end # def to_h @table.dup end # Access a value in the OpenStruct by key, like a Hash. # This increases OpenStruct's "duckiness". # # o = OpenStruct.new # o.t = 4 # o['t'] #=> 4 # def [](key) key = key.to_sym unless key.is_a?(Symbol) @table[key] end # Set a value in the OpenStruct by key, like a Hash. # # o = OpenStruct.new # o['t'] = 4 # o.t #=> 4 # def []=(key,val) raise TypeError, "can't modify frozen #{self.class}", caller(1) if self.frozen? key = key.to_sym unless key.is_a?(Symbol) @table[key]=val end # Provides access to an OpenStruct's inner table. # # o = OpenStruct.new # o.a = 1 # o.b = 2 # o.instance_delegate.map { |k, v| "#{k} #{v}" } # #=> ["a 1", "b 2"] # def instance_delegate @table end # alias ostruct_delegate instance_delegate # Insert/update hash data on the fly. # # o = OpenStruct.new # o.ostruct_update(:a => 2) # o.a #=> 2 # def ostruct_update(other) raise TypeError, "can't modify frozen #{self.class}", caller(1) if self.frozen? ##other = other.to_hash #to_h ? for k,v in other @table[k.to_sym] = v end self end # Merge hash data creating a new OpenStruct object. # # o = OpenStruct.new # x = o.ostruct_merge(:a => 2) # x.a #=> 2 # def ostruct_merge(other) o = dup o.ostruct_update(other) o end #-- # TO BE DEPRECATED # Must consider that accessing instance_delegate instead can be dangerous. # Might we us a Functor to ensure the table keys are always symbols? #++ # Insert/update hash data on the fly. # # o = OpenStruct.new # o.ostruct_update(:a => 2) # o.a #=> 2 # def __update__(other) raise TypeError, "can't modify frozen #{self.class}", caller(1) if self.frozen? ##other = other.to_hash #to_h? for k,v in other @table[k.to_sym] = v end self end # Merge hash data creating a new OpenStruct object. # # o = OpenStruct.new # x = o.ostruct_merge(:a => 2) # x.a #=> 2 # def __merge__(other) o = dup o.__update__(other) o end # def to_ostruct self end end class Hash # Turns a hash into a generic object using an OpenStruct. # # o = {'a' => 1}.to_ostruct # o.a #=> 1 # def to_ostruct OpenStruct.new(self) end # Like to_ostruct but recusively objectifies all hash elements as well. # # o = {'a' => { 'b' => 1 }}.to_ostruct_recurse # o.a.b #=> 1 # # The +exclude+ parameter is used internally to prevent infinite # recursion and is not intended to be utilized by the end-user. # But for more advance use, if there is a particular subhash you # would like to prevent from being converted to an OpoenStruct # then include it in the +exclude+ hash referencing itself. Eg. # # h = { 'a' => { 'b' => 1 } } # o = h.to_ostruct_recurse( { h['a'] => h['a'] } ) # o.a['b'] #=> 1 # # CREDIT: Alison Rowland, Jamie Macey, Mat Schaffer def to_ostruct_recurse(exclude={}) return exclude[self] if exclude.key?( self ) o = exclude[self] = OpenStruct.new h = self.dup each_pair do |k,v| h[k] = v.to_ostruct_recurse( exclude ) if v.respond_to?(:to_ostruct_recurse) end o.__update__(h) end end class NilClass # Create an empty OpenStruct object. def to_ostruct OpenStruct.new end end # Copyright (c) 2005 Thomas Sawyer (Ruby License) facets-2.9.3/lib/standard/facets/platform.rb0000644000004100000410000002041711714455226021021 0ustar www-datawww-datarequire 'facets/rbconfig' unless defined?(RUBY_ENGINE) RUBY_ENGINE = 'ruby' end # Platform class # # Original version from RubyGems, Copyright (c) 2007 Eric Hodel class Platform # A pure-ruby gem that may use Gem::Specification#extensions to build # binary files. RUBY = 'ruby' # A platform-specific gem that is built for the packaging ruby's platform. # This will be replaced with Gem::Platform::local. CURRENT = 'current' @local = nil @supported = nil # attr_accessor :cpu # attr_accessor :os # attr_accessor :version ##RbConfig = Config unless defined? ::RbConfig ##DEPRECATED_CONSTS = [ ## :DARWIN, ## :LINUX_586, ## :MSWIN32, ## :PPC_DARWIN, ## :WIN32, ## :X86_LINUX ##] # Array of supported platforms (ie. pure-Ruby and local platform). def self.supported @suported ||= [Platform::RUBY, Platform.local] end ##def self.const_missing(name) # TODO remove six months from 2007/12 ## if DEPRECATED_CONSTS.include? name then ## raise NameError, "#{name} has been removed, use CURRENT instead" ## else ## super ## end ##end # def self.local arch = Config::CONFIG['arch'] arch = "#{arch}_60" if arch =~ /mswin32$/ @local ||= new(arch) end # def self.match(platform) supported.any? do |local_platform| platform.nil? or local_platform == platform or (local_platform != Platform::RUBY and local_platform =~ platform) end end # def self.new(arch) # :nodoc: case arch when Platform::CURRENT then Platform.local when Platform::RUBY, nil, '' then Platform::RUBY else super end end # def initialize(arch) case arch when Array then @cpu, @os, @version = arch when String then arch = arch.split '-' if arch.length > 2 and arch.last !~ /\d/ then # reassemble x86-linux-gnu extra = arch.pop arch.last << "-#{extra}" end cpu = arch.shift @cpu = case cpu when /i\d86/ then 'x86' else cpu end if arch.length == 2 and arch.last =~ /^\d+$/ then # for command-line @os, @version = arch return end os, = arch @cpu, os = nil, cpu if os.nil? # legacy jruby @os, @version = case os when /aix(\d+)/ then [ 'aix', $1 ] when /cygwin/ then [ 'cygwin', nil ] when /darwin(\d+)?/ then [ 'darwin', $1 ] when /freebsd(\d+)/ then [ 'freebsd', $1 ] when /hpux(\d+)/ then [ 'hpux', $1 ] when /^java$/, /^jruby$/ then [ 'java', nil ] when /^java([\d.]*)/ then [ 'java', $1 ] when /linux/ then [ 'linux', $1 ] when /mingw32/ then [ 'mingw32', nil ] when /(mswin\d+)(\_(\d+))?/ then os, version = $1, $3 @cpu = 'x86' if @cpu.nil? and os =~ /32$/ [os, version] when /netbsdelf/ then [ 'netbsdelf', nil ] when /openbsd(\d+\.\d+)/ then [ 'openbsd', $1 ] when /solaris(\d+\.\d+)/ then [ 'solaris', $1 ] # test when /^(\w+_platform)(\d+)/ then [ $1, $2 ] else [ 'unknown', nil ] end when Platform then @cpu = arch.cpu @os = arch.os @version = arch.version else raise ArgumentError, "invalid argument #{arch.inspect}" end end # def inspect "#s:0x%x @cpu=%p, @os=%p, @version=%p>" % [self.class, object_id, *to_a] end # def to_a [@cpu, @os, @version] end # def to_s to_a.compact.join '-' end # def ==(other) self.class === other and @cpu == other.cpu and @os == other.os and @version == other.version end # def ===(other) return nil unless Platform === other # cpu (@cpu == 'universal' or other.cpu == 'universal' or @cpu == other.cpu) and # os @os == other.os and # version (@version.nil? or other.version.nil? or @version == other.version) end # def =~(other) case other when Platform then # nop when String then # This data is from http://gems.rubyforge.org/gems/yaml on 19 Aug 2007 other = case other when /^i686-darwin(\d)/ then ['x86', 'darwin', $1] when /^i\d86-linux/ then ['x86', 'linux', nil] when 'java', 'jruby' then [nil, 'java', nil] when /mswin32(\_(\d+))?/ then ['x86', 'mswin32', $2] when 'powerpc-darwin' then ['powerpc', 'darwin', nil] when /powerpc-darwin(\d)/ then ['powerpc', 'darwin', $1] when /sparc-solaris2.8/ then ['sparc', 'solaris', '2.8'] when /universal-darwin(\d)/ then ['universal', 'darwin', $1] else other end other = Platform.new other else return nil end self === other end # B Y T E O R D E R # Byte order of CPU. Determine byte order of underlying machine. # # Examines the byte order of the underlying machine. Returns :big # if Big Endian and :little if Little Endian. # # TODO: This doesn't work well apearently. We need to use a chart for possible # cpus instead, maybe. def byte_order if [0x12345678].pack("L") == "\x12\x34\x56\x78" :big else :little end end # alias_method :byteorder, :byte_order # def little_endian? byte_order == :little end # def big_endian? byte_order == :big end # R U B Y E N G I N E # Return the name of the ruby interpreter. def interpreter @interpreter ||= ( if RUBY_PLATFORM == 'parrot' 'cardinal' elsif RUBY_ENGINE == 'ruby' if RUBY_DESCRIPTION =~ /Enterprise/i 'ree' else 'mri' end else RUBY_ENGINE.to_s # jruby, rbx, ironruby, macruby, etc. end ) end def mri? 'mri' === interpreter end alias official_ruby? mri? alias ruby? mri? def jruby? 'jruby' === interpreter end alias java? jruby? def rubinius? 'rbx' === interpreter end alias rbx? rubinius? def ree? 'ree' === interpreter end alias enterprise? ree? def ironruby? 'ironruby' === interpreter end alias iron_ruby? ironruby? def cardinal? 'cardinal' === interpreter end alias parrot? cardinal? alias perl? cardinal? # O P E R A T I N G S Y S T E M def host_os RbConfig::CONFIG['host_os'] end def linux? host_os =~ /linux|cygwin/ end def mac? host_os =~ /mac|darwin/ end def bsd? host_os =~ /bsd/ end def windows? host_os =~ /mswin|mingw/ end def solaris? host_os =~ /solaris|sunos/ end # TODO: who knows what symbian returns? def symbian? host_os =~ /symbian/ end # def posix? linux? or mac? or bsd? or solaris? or begin fork do end true rescue NotImplementedError, NoMethodError false end end end # Current CPU's Byte Order #BYTE_ORDER = RbConfig.byte_order # Current CPU #CPU = RbConfig.platform.cpu # Current Operating System #OS = RbConfig.platform.os # Current Operating System Version #OS_VERSION = RbConfig.platform.version =begin # platform def current_platform arch = Config::CONFIG['arch'] #cpu, os = arch.split '-', 2 return match_platform(arch) end # def match_platform(arch) cpu, os = arch.split '-', 2 cpu, os = nil, cpu if os.nil? # java cpu = case cpu when /i\d86/ then 'x86' else cpu end os = case os when /cygwin/ then [ 'cygwin', nil ] when /darwin(\d+)?/ then [ 'darwin', $1 ] when /freebsd(\d+)/ then [ 'freebsd', $1 ] when /^java$/ then [ 'java', nil ] when /^java([\d.]*)/ then [ 'java', $1 ] when /linux/ then [ 'linux', $1 ] when /mingw32/ then [ 'mingw32', nil ] when /mswin32/ then [ 'mswin32', nil ] when /openbsd(\d+\.\d+)/ then [ 'openbsd', $1 ] when /solaris(\d+\.\d+)/ then [ 'solaris', $1 ] else [ 'unknown', nil ] end [cpu, os].flatten.compact.join("-") end =end facets-2.9.3/lib/standard/facets/random.rb0000644000004100000410000002627011714455226020460 0ustar www-datawww-datarequire 'facets/hash/zip' require 'facets/string/shatter' require 'facets/kernel/maybe' # = Randomization Extensions # # This library extends Array, String, Hash and other classes with randomization # methods. Most of the methods are of one of two kinds. Either they "pick" a # random element from the reciever or they randomly "shuffle" the reciever. # # The most common example is Array#shuffle, which simply randmomizes the # order of an array's elements. # # [1,2,3].shuffle #~> [2,3,1] # # The other methods do similar things for their respective classes. # # The classes are all extended via mixins which have been created within # Ruby's Random class. # # Credit for this work is due to: # # * Ilmari Heikkinen # * Christian Neukirchen # * Thomas Sawyer # # NOTE: Inline QED tests are almost pointless here b/c... yea, it's random. # So indtead of the usual `#=>` we use `#~>` which means approx. equal and # prevens QED from making a hard assertion. class Random class << self # Alias for Kernel#rand. alias_method :number, :rand public :number end ##def self.number(*args) ## ::Kernel.rand(*args) ##end # Module method to generate a random letter. # # Random.letter #~> "q" # Random.letter #~> "r" # Random.letter #~> "a" # def self.letter (Random.number(26) + (Random.number(2) == 0 ? 65 : 97) ).chr end # module RangeExtensions # Return a random element from the range. # # (1..4).at_rand #~> 2 # (1..4).at_rand #~> 4 # # (1.5..2.5).at_rand #~> 2.06309842754533 # (1.5..2.5).at_rand #~> 1.74976944931541 # # ('a'..'z').at_rand #~> 'q' # ('a'..'z').at_rand #~> 'f' # # CREDIT: Lavir the Whiolet, Thomas Sawyer def at_rand first, last = first(), last() if first.respond_to?(:random_delta) # TODO: work on this!!! begin first.random_delta(last, exclude_end?) rescue to_a.at_rand end else to_a.at_rand end ##elsif first.respond_to?(:succ) ## # optimized algorithm ## if (Fixnum === first || Bignum === first) && ## (Fixnum === last || Bignum === last) ## last -= 1 if exclude_end? ## return nil if last < first ## return Random.number(last - first + 1) + first ## end ## # standard algorithm ## return to_a.at_rand ##elsif Numeric === first && Numeric === last ## return nil if last < first ## return nil if exclude_end? && last == first ## return (last - first) * Random.number + first ##else ## return nil ##end end end # module IntegerExtensions # def random_delta(last, exclude_end) first = self last -= 1 if exclude_end return nil if last < first return Random.number(last - first + 1) + first end end # module NumericExtensions # def random_delta(last, exclude_end) first = self return nil if last < first return nil if exclude_end && last == first return (last - first) * Random.number + first end end # module ArrayExtensions # Return a random element from the array. # # [1, 2, 3, 4].at_rand #~> 2 # [1, 2, 3, 4].at_rand #~> 4 # def at_rand at(Random.number(size)) end # Same as #at_rand, but acts in place removing a # random element from the array. # # a = [1,2,3,4] # a.at_rand! #~> 2 # a #~> [1,3,4] # def at_rand! return delete_at( Random.number( size ) ) end # Similar to #at_rand, but will return an array of randomly # picked exclusive elements if given a number. def pick(n=nil) if n a = self.dup a.pick!(n) else at(Random.number(size)) end end # Similar to #at_rand!, but given a number will return # an array of exclusive elements. def pick!(n=nil) if n if n > self.size r = self.dup self.replace([]) r else r = [] n.times { r << delete_at(Random.number(size)) } r end else delete_at(Random.number(size)) end end # Random index. # def rand_index Random.number(size) end # Returns a random subset of an Array. If a _number_ # of elements is specified then returns that number of # elements, otherwise returns a random number of elements # upto the size of the Array. # # By defualt the returned values are exclusive of # each other, but if _exclusive_ is set to false, # the same values can be choosen more than once. # # When _exclusive_ is true (the default) and the # _number_ given is greater than the size of the array, # then all values are returned. # # [1, 2, 3, 4].rand_subset(1) #~> [2] # [1, 2, 3, 4].rand_subset(4) #~> [2, 1, 3, 4] # [1, 2, 3, 4].rand_subset #~> [1, 3, 4] # [1, 2, 3, 4].rand_subset #~> [2, 3] # def rand_subset( number=nil, exclusive=true ) number = Random.number(size) unless number number = number.to_int #return self.dup if (number >= size and exlusive) return sort_by{rand}.slice(0,number) if exclusive ri =[]; number.times { |n| ri << Random.number(size) } return values_at(*ri) end # Randomize the order of an array. # # [1,2,3,4].shuffle #~> [2,4,1,3] # def shuffle dup.shuffle! #sort_by{Random.number} end # As with #shuffle but modifies the array in place. # The algorithm used here is known as a Fisher-Yates shuffle. # # a = [1,2,3,4] # a.shuffle! # # a #~> [2,4,1,3] # # CREDIT Niel Spring def shuffle! s = size each_index do |j| i = Random.number(s-j) #self[j], self[j+i] = self[j+i], self[j] tmp = self[j] self[j] = self[j+i] self[j+i] = tmp end self end end # module HashExtensions # Returns a random key. # # {:one => 1, :two => 2, :three => 3}.pick_key #~> :three # def rand_key keys.at(Random.number(keys.size)) end # Delete a random key-value pair, returning the key. # # a = {:one => 1, :two => 2, :three => 3} # a.rand_key! #~> :two # a #~> {:one => 1, :three => 3} # def rand_key! k,v = rand_pair delete(k) return k end alias_method( :pick_key, :rand_key! ) # Returns a random key-value pair. # # {:one => 1, :two => 2, :three => 3}.pick #~> [:one, 1] # def rand_pair k = rand_key return k, fetch(k) end # Deletes a random key-value pair and returns that pair. # # a = {:one => 1, :two => 2, :three => 3} # a.rand_pair! #~> [:two, 2] # a #~> {:one => 1, :three => 3} # def rand_pair! k,v = rand_pair delete( k ) return k,v end alias_method( :pick_pair, :rand_pair! ) # Returns a random hash value. # # {:one => 1, :two => 2, :three => 3}.rand_value #~> 2 # {:one => 1, :two => 2, :three => 3}.rand_value #~> 1 # def rand_value fetch(rand_key) end # Deletes a random key-value pair and returns the value. # # a = {:one => 1, :two => 2, :three => 3} # a.at_rand! #~> 2 # a #~> {:one => 1, :three => 3} # def rand_value! k,v = rand_pair delete( k ) return v end alias_method( :pick, :rand_value! ) alias_method( :at_rand, :rand_value ) alias_method( :at_rand!, :rand_value! ) # Returns a copy of the hash with _values_ arranged # in new random order. # # h = {:a=>1, :b=>2, :c=>3} # h.shuffle #~> {:b=>2, :c=>1, :a>3} # def shuffle ::Hash.zip( keys.sort_by{Random.number}, values.sort_by{Random.number} ) end # Destructive shuffle_hash. Arrange the values in # a new random order. # # h = {:a => 1, :b => 2, :c => 3} # h.shuffle! # h #~> {:b=>2, :c=>1, :a=>3} # def shuffle! self.replace(shuffle) end end # module StringExtensions # def self.included(base) base.extend(Self) end # Class-level methods. module Self # Returns a randomly generated string. One possible use is # password initialization. Takes a max legnth of characters # (default 8) and an optional valid char Regexp (default /\w\d/). # # String.random #~> 'dd4qed4r' # # CREDIT George Moschovitis #-- # TODO: This is not very efficient. Better way? #++ def random(max_length = 8, char_re = /[\w\d]/) raise ArgumentError.new('char_re must be a regular expression!') unless char_re.is_a?(Regexp) string = "" while string.length < max_length ch = Random.number(255).chr string << ch if ch =~ char_re end return string end end # Return a random separation of the string. # Default separation is by charaacter. # # "Ruby rules".at_rand(' ') #~> ["Ruby"] # def at_rand( separator=// ) #separator = self.class.patterns( separator ) self.split(separator,-1).at_rand end # Return a random separation while removing it # from the string. Default separation is by character. # # s = "Ruby rules" # s.at_rand!(' ') #~> "Ruby" # s #~> "rules" # def at_rand!( separator=// ) #separator = self.class.patterns( separator ) a = self.shatter( separator ) w = []; a.each_with_index { |s,i| i % 2 == 0 ? w << s : w.last << s } i = Random.number(w.size) r = w.delete_at( i ) self.replace( w.join('') ) return r end # Return a random byte of _self_. # # "Ruby rules".rand_byte #~> 121 # def rand_byte self[Random.number(size)] end # Destructive rand_byte. Delete a random byte of _self_ and return it. # # s = "Ruby rules" # s.rand_byte! #~> 121 # s #~> "Rub rules" # def rand_byte! i = Random.number(size) rv = self[i,1] self[i,1] = '' rv end # Return a random string index. # # "Ruby rules".rand_index #~> 3 # def rand_index Random.number(size) end # Return the string with seperated sections arranged # in a random order. The default seperation is by character. # # "Ruby rules".shuffle #~> "e lybRsuur" # def shuffle(separator=//) split(separator).shuffle.join('') end # In place version of shuffle. # def shuffle!(separator=//) self.replace( shuffle(separator) ) end end end class Range ; include Random::RangeExtensions ; end class Array ; include Random::ArrayExtensions ; end class Hash ; include Random::HashExtensions ; end class String ; include Random::StringExtensions ; end class Integer ; include Random::IntegerExtensions ; end class Numeric ; include Random::NumericExtensions ; end # Copyright (c) 2005 Ilmari Heikkinen, Christian Neukirchen, Thomas Sawyer facets-2.9.3/lib/standard/facets/digest/0000755000004100000410000000000011714455226020123 5ustar www-datawww-datafacets-2.9.3/lib/standard/facets/digest/salted_digest.rb0000644000004100000410000000170711714455226023270 0ustar www-datawww-datarequire 'digest' require 'facets/string/random_binary' module Digest module Instance # CREDIT: Guido De Rosa def salted_digest(str='', salt=:auto) if salt == :auto salt = String.random_binary(digest_length) end digest(str + salt) + salt end # CREDIT: Guido De Rosa def salted_hexdigest(str, salt) Digest.hexencode(salted_digest(str, salt)) end # CREDIT: Guido De Rosa def salted_base64digest(str, salt) [salted_digest(str, salt)].pack('m0') end end class Class # CREDIT: Guido De Rosa def self.salted_digest(str, salt=:auto, *args) new(*args).salted_digest(str, salt) end # CREDIT: Guido De Rosa def self.salted_hexdigest(str, salt=:auto, *args) new(*args).salted_hexdigest(str, salt) end # CREDIT: Guido De Rosa def self.salted_base64digest(str, salt=:auto, *args) new(*args).salted_base64digest(str, salt) end end end facets-2.9.3/lib/standard/facets/digest/base64digest.rb0000644000004100000410000000122611714455226022735 0ustar www-datawww-datarequire 'digest' module Digest module Instance # For Ruby < 1.9.2 unless instance_methods.include? :base64digest # From Ruby 1.9.2 source def base64digest(str = nil) [str ? digest(str) : digest].pack('m0') end end unless instance_methods.include? :base64digest! # From Ruby 1.9.2 source def base64digest! [digest!].pack('m0') end end end class Class # For Ruby < 1.9.2 unless methods.include? :base64digest # From Ruby 1.9.2 source def self.base64digest(str, *args) [self.digest(str, *args)].pack('m0') end end end end facets-2.9.3/lib/standard/facets/fileutils.rb0000644000004100000410000000067511714455226021201 0ustar www-datawww-data# TODO: Deprecate #safe_ln, if #ln has been fixed to do this. require 'fileutils' require 'facets/fileutils/amass' require 'facets/fileutils/cp_rx' require 'facets/fileutils/ln_r' require 'facets/fileutils/outofdate' require 'facets/fileutils/safe_ln' require 'facets/fileutils/slice' # includes head and tail require 'facets/fileutils/stage' require 'facets/fileutils/wc' require 'facets/fileutils/whereis' require 'facets/fileutils/which' facets-2.9.3/lib/standard/facets/date.rb0000644000004100000410000003162211714455226020112 0ustar www-datawww-datarequire 'date' require 'facets/time/stamp' # = Date # # This new version of Date extension has been largely improved by # porting some of the methods used by ActiveSupport. The old version # already had much in common with the Active Support library, so it # was decided to take it a step further in that direction for the # sake of interoparability. # # Hopefully most of these methods will find there way into Ruby's # own standard library eventually. # # The biggest difference with ActiveSupport is the lack of many # of the "English-esque" methods, and that we use #stamp with # Date::FORMAT, instead of #to_formmated_s with Date::DATE_FORMATS. # We do not override the standard #to_s method like ActiveSupport does. class Date FORMAT = { :short => "%e %b", :long => "%B %e, %Y", :db => "%Y-%m-%d", :number => "%Y%m%d", :rfc822 => "%e %b %Y", :default => "%Y-%m-%d", nil => "%Y-%m-%d" } # Returns a new Date representing the date 1 day ago (i.e. yesterday's date). def self.yesterday ::Date.today.yesterday end # Returns a new Date representing the date 1 day after today (i.e. tomorrow's date). def self.tomorrow ::Date.today.tomorrow end # Returns Time.zone.today when config.time_zone is set, otherwise just returns Date.today. def self.current ::Time.zone_default ? ::Time.zone.today : ::Date.today end # A method to keep Time, Date and DateTime instances interchangeable # on conversions. In this case, it simply returns +self+. def to_date self end unless method_defined?(:to_date) # 1.9+ ? # Converts a Date instance to a DateTime, where the time is set to the beginning of the day # and UTC offset is set to 0. # # date = Date.new(2007, 11, 10) # Sat, 10 Nov 2007 # date.to_datetime # Sat, 10 Nov 2007 00:00:00 0000 # def to_datetime ::DateTime.civil(year, month, day, 0, 0, 0, 0) end unless method_defined?(:to_datetime) # 1.9+ ? # Converts a Date instance to a Time, where the time is set to the beginning of the day. # The timezone can be either :local or :utc (default :local). # # date = Date.new(2007, 11, 10) # Sat, 10 Nov 2007 # # date.to_time # Sat Nov 10 00:00:00 0800 2007 # date.to_time(:local) # Sat Nov 10 00:00:00 0800 2007 # # date.to_time(:utc) # Sat Nov 10 00:00:00 UTC 2007 # def to_time(form=:local) ::Time.send(form, year, month, day) ##::Time.send("#{form}_time", year, month, day) end # def xmlschema to_time.xmlschema end # Returns the number of days in the date's month. # # Date.new(2004,2).days_in_month #=> 29 # # CREDIT: Ken Kunz. def days_in_month Date.civil(year, month, -1).day end def days_of_month (1..days_in_month).to_a end # Get the month name for this date object # # CREDIT: Benjamin Oakes def month_name MONTHNAMES[self.month] end # Convert to a formatted string. See DATE_FORMATS for predefined formats. # # This method is aliased to to_s. # # date = Date.new(2007, 11, 10) # Sat, 10 Nov 2007 # # date.stamp(:db) # => "2007-11-10" # date.stamp(:short) # => "10 Nov" # date.stamp(:long) # => "November 10, 2007" # date.stamp(:rfc822) # => "10 Nov 2007" # # == Adding your own formats to stamp # You can add your own formats to the Date::FORMAT hash. # Use the format name as the hash key and a strftime string # as the value. Eg. # # Date::FORMAT[:month_and_year] = "%B %Y" # def stamp(format=:default) if formatter = FORMAT[format] strftime(formatter) else to_s end end ## Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005" ##def inspect ## strftime("%a, %d %b %Y") ##end # Provides precise Date calculations for years, months, and days. # The +options+ parameter takes a hash with any of these keys: # :years, :months, :weeks, :days. def advance(options) d = self d = d >> options.delete(:years) * 12 if options[:years] d = d >> options.delete(:months) if options[:months] d = d + options.delete(:weeks) * 7 if options[:weeks] d = d + options.delete(:days) if options[:days] d end # Returns a new Date where one or more of the elements have been changed # according to the +options+ parameter. # # Date.new(2007, 5, 12).change(:day=>1) # Date.new(2007, 5, 1) # Date.new(2007, 5, 12).change(:year=>2005, :month=>1) # Date.new(2005, 1, 12) # def change(options) ::Date.new( options[:year] || self.year, options[:month] || self.month, options[:day] || self.day ) end # Converts Date to a Time (or DateTime if necessary) with the time portion # set to the beginning of the day (0:00) and then subtracts the specified # number of seconds def ago(seconds) to_time.since(-seconds) end # Converts Date to a Time (or DateTime if necessary) with the time portion # set to the beginning of the day (0:00) and then adds the specified number # of seconds. def since(seconds) to_time.since(seconds) end alias :in :since # Converts Date to a Time (or DateTime if necessary) with the time portion # set to the beginning of the day (0:00). def beginning_of_day to_time end alias :midnight :beginning_of_day # Convenience method which returns a new Date/DateTime representing the # time 1 day ago. def yesterday self - 1 end # Convenience method which returns a new Date/DateTime representing # the time 1 day since the instance time. def tomorrow self + 1 end end class DateTime # def self.local_offset ::Time.local(2007).utc_offset.to_r / 86400 end def future? self > ::DateTime.current end def past? self < ::DateTime.current end # Converts self to a Ruby Date object; time portion is discarded def to_date ::Date.new(year, month, day) end # Attempts to convert self to a Ruby Time object; returns self if # out of range of Ruby Time class. If self has an offset other than 0, # self will just be returned unaltered, since there's no clean way # to map it to a Time. def to_time self.offset == 0 ? ::Time.utc_time(year, month, day, hour, min, sec) : self end # To be able to keep Times, Dates and DateTimes interchangeable on conversions def to_datetime self end # Convert to a formatted string. See Time::FORMAT for predefined formats. # # This method is aliased to to_s. # # datetime = DateTime.civil(2007,12,4,0,0,0,0) # Tue, 04 Dec 2007 00:00:00 +0000 # # datetime.stamp(:db) # => "2007-12-04 00:00:00" # datetime.stamp(:db) # => "2007-12-04 00:00:00" # datetime.stamp(:number) # => "20071204000000" # datetime.stamp(:short) # => "04 Dec 00:00" # datetime.stamp(:long) # => "December 04, 2007 00:00" # datetime.stamp(:rfc822) # => "Tue, 04 Dec 2007 00:00:00 +0000" # # == Adding your own datetime formats to stamp # # DateTime formats are shared with Time. You can add your own to the # Time::FORMAT hash. Use the format name as the hash key and # a strftime string as the value. Eg. # # Time::FORMAT[:month_and_year] = "%B %Y" # def stamp(format=:default) if formatter = ::Time::FORMAT[format] strftime(formatter) else to_s end end # Seconds since midnight: DateTime.now.seconds_since_midnight def seconds_since_midnight self.sec + (self.min * 60) + (self.hour * 3600) end # Returns a new DateTime where one or more of the elements have been # changed according to the +options+ parameter. The time options # (hour, minute, sec) reset cascadingly, so if only the hour is # passed, then minute and sec is set to 0. If the hour and # minute is passed, then sec is set to 0. def change(options) ::DateTime.civil( options[:year] || self.year, options[:month] || self.month, options[:day] || self.day, options[:hour] || self.hour, options[:min] || (options[:hour] ? 0 : self.min), options[:sec] || ((options[:hour] || options[:min]) ? 0 : self.sec), options[:offset] || self.offset, options[:start] || self.start ) end # Uses Date to provide precise Time calculations for years, months, and days. # The +options+ parameter takes a hash with any of these keys: :years, # :months, :weeks, :days, :hours, # :minutes, :seconds. def advance(options) d = to_date.advance(options) datetime_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day) seconds_to_advance = (options[:seconds] || 0) + (options[:minutes] || 0) * 60 + (options[:hours] || 0) * 3600 seconds_to_advance == 0 ? datetime_advanced_by_date : datetime_advanced_by_date.since(seconds_to_advance) end # Returns a new DateTime representing the time a number of seconds ago # Do not use this method in combination with x.months, use months_ago instead! def ago(seconds) self.since(-seconds) end # Returns a new DateTime representing the time a number of seconds since the instance time # Do not use this method in combination with x.months, use months_since instead! def since(seconds) self + Rational(seconds.round, 86400) end alias :in :since # Returns a new DateTime representing the start of the day (0:00) def beginning_of_day change(:hour => 0) end alias :midnight :beginning_of_day # Returns a new DateTime representing the end of the day (23:59:59) def end_of_day change(:hour => 23, :min => 59, :sec => 59) end # Adjusts DateTime to UTC by adding its offset value; offset is set to 0 # # Example: # # DateTime.civil(2005,2,21,10,11,12,Rational(-6, 24)) # Mon, 21 Feb 2005 10:11:12 -0600 # DateTime.civil(2005,2,21,10,11,12,Rational(-6, 24)).utc # Mon, 21 Feb 2005 16:11:12 +0000 # def utc new_offset(0) end alias_method :getutc, :utc # Returns true if offset == 0 def utc? offset == 0 end # Returns the offset value in seconds def utc_offset (offset * 86400).to_i end # Converts datetime to an appropriate format for use in XML def xmlschema strftime("%Y-%m-%dT%H:%M:%S%Z") end unless method_defined?(:xmlschema) # 1.9+ ? # Converts self to a floating-point number of seconds since the Unix epoch def to_f days_since_unix_epoch = self - ::DateTime.civil(1970) (days_since_unix_epoch * 86_400).to_f end end class Time # def self.local_time(*args) time_with_datetime_fallback(:local, *args) end # def self.utc_time(*args) time_with_datetime_fallback(:utc, *args) end # def self.time_with_datetime_fallback(utc_or_local, year, month=1, day=1, hour=0, min=0, sec=0, usec=0) ::Time.send(utc_or_local, year, month, day, hour, min, sec, usec) rescue offset = utc_or_local.to_sym == :local ? ::DateTime.local_offset : 0 ::DateTime.civil(year, month, day, hour, min, sec, offset) end public :to_date public :to_datetime # Converts a Time object to a Date, dropping hour, minute, and second precision. # # my_time = Time.now # Mon Nov 12 22:59:51 -0500 2007 # my_time.to_date # Mon, 12 Nov 2007 # # your_time = Time.parse("1/13/2009 1:13:03 P.M.") # Tue Jan 13 13:13:03 -0500 2009 # your_time.to_date # Tue, 13 Jan 2009 # def to_date ::Date.new(year, month, day) end ## # Convert a Time to a Date. Time is a superset of Date. ## # It is the year, month and day that are carried over. ## ## def to_date ## require 'date' # just in case ## jd = Date.__send__(:civil_to_jd, year, mon, mday, Date::ITALY) ## Date.new!(Date.__send__(:jd_to_ajd, jd, 0, 0), 0, Date::ITALY) ## end # Converts a Time instance to a Ruby DateTime instance, preserving UTC offset. # # my_time = Time.now # Mon Nov 12 23:04:21 -0500 2007 # my_time.to_datetime # Mon, 12 Nov 2007 23:04:21 -0500 # # your_time = Time.parse("1/13/2009 1:13:03 P.M.") # Tue Jan 13 13:13:03 -0500 2009 # your_time.to_datetime # Tue, 13 Jan 2009 13:13:03 -0500 # def to_datetime ::DateTime.civil(year, month, day, hour, min, sec, Rational(utc_offset, 86400)) end end class String # def to_time(form = :utc) ::Time.__send__("#{form}_time", *::Date._parse(self, false).values_at(:year, :mon, :mday, :hour, :min, :sec).map{|arg| arg || 0 }) end # Convert string to DateTime. def to_datetime date = ::Date._parse(self, false).values_at(:year, :mon, :mday, :hour, :min, :sec).map { |arg| arg || 0 } ::DateTime.civil(*date) end # Parse data from string. def to_date #::Date::civil(*ParseDate.parsedate(self)[0..2]) ::Date.new(*::Date._parse(self, false).values_at(:year, :mon, :mday)) end end facets-2.9.3/lib/standard/facets/multiton.rb0000644000004100000410000002233611714455226021052 0ustar www-datawww-data# = Multiton # # == Synopsis # # Multiton design pattern ensures only one object is allocated for a given state. # # The 'multiton' pattern is similar to a singleton, but instead of only one # instance, there are several similar instances. It is useful when you want to # avoid constructing objects many times because of some huge expense (connecting # to a database for example), require a set of similar but not identical # objects, and cannot easily control how many times a contructor may be called. # # class SomeMultitonClass # include Multiton # attr :arg # def initialize(arg) # @arg = arg # end # end # # a = SomeMultitonClass.new(4) # b = SomeMultitonClass.new(4) # a and b are same object # c = SomeMultitonClass.new(2) # c is a different object # # == Previous Behavior # # In previous versions of Multiton the #new method was made # private and #instance had to be used in its stay --just like Singleton. # But this is less desirable for Multiton since Multitions can # have multiple instances, not just one. # # So instead Multiton now defines #create as a private alias of # the original #new method (just in case it is needed) and then # defines #new to handle the multiton; #instance is provided # as an alias for it. # #-- # So if you must have the old behavior, all you need do is re-alias # #new to #create and privatize it. # # class SomeMultitonClass # include Multiton # alias_method :new, :create # private :new # ... # end # # Then only #instance will be available for creating the Multiton. #++ # # == How It Works # # A pool of objects is searched for a previously cached object, # if one is not found we construct one and cache it in the pool # based on class and the args given to the contructor. # # A limitation of this approach is that it is impossible to # detect if different blocks were given to a contructor (if it takes a # block). So it is the constructor arguments _only_ which determine # the uniqueness of an object. To workaround this, define the _class_ # method ::multiton_id. # # def SomeMultitonClass.multiton_id(*args, &block) # # ... # end # # Which should return a hash key used to identify the object being # constructed as (not) unique. # # == Authors # # * Christoph Rippel # * Thomas Sawyer # # = Copying # # Copyright (c) 2007 Christoph Rippel, Thomas Sawyer # # Ruby License # # This module is free software. You may use, modify, and/or redistribute this # software under the same terms as Ruby. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. require 'thread' # = Multiton # # Multiton design pattern ensures only one object is allocated for a given state. # # The 'multiton' pattern is similar to a singleton, but instead of only one # instance, there are several similar instances. It is useful when you want to # avoid constructing objects many times because of some huge expense (connecting # to a database for example), require a set of similar but not identical # objects, and cannot easily control how many times a contructor may be called. # # class SomeMultitonClass # include Multiton # attr :arg # def initialize(arg) # @arg = arg # end # end # # a = SomeMultitonClass.new(4) # b = SomeMultitonClass.new(4) # a and b are same object # c = SomeMultitonClass.new(2) # c is a different object # # == How It Works # # A pool of objects is searched for a previously cached object, # if one is not found we construct one and cache it in the pool # based on class and the args given to the contructor. # # A limitation of this approach is that it is impossible to # detect if different blocks were given to a contructor (if it takes a # block). So it is the constructor arguments _only_ which determine # the uniqueness of an object. To workaround this, define the _class_ # method ::multiton_id. # # def SomeMultitonClass.multiton_id(*args, &block) # # ... # end # # Which should return a hash key used to identify the object being # constructed as (not) unique. module Multiton # Disable build-in copying methods. def clone raise TypeError, "can't clone Multiton #{self}" ##self end def dup raise TypeError, "can't dup Multiton #{self}" ##self end # Default marshalling strategy. protected def _dump(depth=-1) Marshal.dump(@multiton_initializer) end # Mutex to safely store multiton instances. class InstanceMutex < Hash #:nodoc: def initialize @global = Mutex.new end def initialized(arg) store(arg, DummyMutex) end def (DummyMutex = Object.new).synchronize yield end def default(arg) @global.synchronize{ fetch(arg){ store(arg, Mutex.new) } } end end # Multiton can be included in another module, in which case that module # effectively becomes a multiton behavior distributor too. This is why we # propogate #included to the base module by putting it in another module. # #-- # def append_features(mod) # # help out people counting on transitive mixins # unless mod.instance_of?(Class) # raise TypeError, "Inclusion of Multiton in module #{mod}" # end # super # end #++ module Inclusive private def included(base) class << base ##alias_method(:new!, :new) unless method_defined?(:new!) ## gracefully handle multiple inclusions of Multiton unless include?(Multiton::MetaMethods) alias_method :new!, :new private :allocate #, :new include Multiton::MetaMethods if method_defined?(:marshal_dump) undef_method :marshal_dump warn "warning: marshal_dump was undefined since it is incompatible with the Multiton pattern" end end end end end extend Inclusive # module MetaMethods include Inclusive def instance(*e, &b) arg = multiton_id(*e, &b) multiton_instance.fetch(arg) do multiton_mutex[arg].synchronize do multiton_instance.fetch(arg) do val = multiton_instance[arg] = new!(*e, &b) #new(*e, &b) val.instance_variable_set(:@multiton_initializer, e, &b) multiton_mutex.initialized(arg) val end end end end alias_method :new, :instance def initialized?(*e, &b) multiton_instance.key?(multiton_id(*e, &b)) end protected def multiton_instance @multiton_instance ||= Hash.new end def multiton_mutex @multiton_mutex ||= InstanceMutex.new end def reinitialize multiton_instance.clear multiton_mutex.clear end def _load(str) instance(*Marshal.load(str)) end private # Default method to to create a key to cache already constructed # instances. In the use case MultitonClass.new(e), MultiClass.new(f) # must be semantically equal if multiton_id(e).eql?(multiton_id(f)) # evaluates to true. def multiton_id(*e, &b) e end def singleton_method_added(sym) super if (sym == :marshal_dump) & singleton_methods.include?('marshal_dump') raise TypeError, "Don't use marshal_dump - rely on _dump and _load instead" end end end end =begin # TODO: Convert this into a real test and/or benchmark. if $0 == __FILE__ ### Simple marshalling test ####### class A def initialize(a,*e) @e = a end include Multiton begin def self.marshal_dump(depth = -1) end rescue => mes p mes class << self; undef marshal_dump end end end C = Class.new(A.clone) s = C.instance('a','b') raise unless Marshal.load(Marshal.dump(s)) == s ### Interdependent initialization example and threading benchmark ### class Regular_SymPlane def self.multiton_id(*e) a,b = e (a+b - 1)*(a+b )/2 + (a > b ? a : b) end def initialize(a,b) klass = self.class if a < b @l = b > 0 ? klass.instance(a,b-1) : nil @r = a > 0 ? klass.instance(a-1,b) : nil else @l = a > 0 ? klass.instance(a-1,b) : nil @r = b > 0 ? klass.instance(a,b-1) : nil end end include Multiton end def nap # Thread.pass sleep(rand(0.01)) end class SymPlane < Regular_SymPlane @m = Mutex.new @count = 0 end class << SymPlane attr_reader :count def reinitialize super @m = Mutex.new @count = 0 end def inherited(sub_class) super sub_class.instance_eval { @m = Mutex.new; @count = 0 } end def multiton_id(*e) nap() super end def new!(*e) # NOTICE!!! super ensure nap() @m.synchronize { p @count if (@count += 1) % 15 == 0 } end def run(k) threads = 0 max = k * (k+1) / 2 puts "" while count() < max Thread.new { threads+= 1; instance(rand(30),rand(30)) } end puts "\nThe simulation created #{threads} threads" end end require 'benchmark' include Benchmark bmbm do |x| x.report('Initialize 465 SymPlane instances') { SymPlane.run(30) } x.report('Reinitialize ') do sleep 3 SymPlane.reinitialize end end end =end facets-2.9.3/lib/standard/facets/multipliers.rb0000644000004100000410000000332611714455226021546 0ustar www-datawww-dataclass Numeric # = Numeric::Multipliers # # Adds methods to Numeric to make working with # magnitudes (kilo, mega, giga, milli, micro, etc.) # # 1.kilo #=> 1000 # 1.milli #=> 0.001 # 1.kibi #=> 1024 # # To display a value in a certain denomination, simply # perform the inverse operation by placing the # multiplier called on unit (1) in the denominator. # # (1000 / 1.kilo) #=> 1 # (1024 / 1.kibi) #=> 1 # # Thanks to Rich Kilmer and bytes.rb which inspired this library. module Multipliers # SI Multipliers def deka ; self * 10 ; end def hecto ; self * 100 ; end def kilo ; self * 1000 ; end def mega ; self * 1000000 ; end def giga ; self * 1000000000 ; end def tera ; self * 1000000000000 ; end def peta ; self * 1000000000000000 ; end def exa ; self * 1000000000000000000 ; end # SI Fractional def deci ; self.to_f / 10 ; end def centi ; self.to_f / 100 ; end def milli ; self.to_f / 1000 ; end def micro ; self.to_f / 1000000 ; end def nano ; self.to_f / 1000000000 ; end def pico ; self.to_f / 1000000000000 ; end def femto ; self.to_f / 1000000000000000 ; end def atto ; self.to_f / 1000000000000000000 ; end # SI Binary def kibi ; self * 1024 ; end def mebi ; self * 1024**2 ; end def gibi ; self * 1024**3 ; end def tebi ; self * 1024**4 ; end def pebi ; self * 1024**5 ; end def exbi ; self * 1024**6 ; end # Bits and Bytes #def bit ; self ; end #def bits ; self ; end #def byte ; self * 8 ; end #def bytes ; self * 8 ; end end include Multipliers end # Copyright (c) 2005 Thomas Sawyer facets-2.9.3/lib/standard/facets/yaml.rb0000644000004100000410000000227311714455226020137 0ustar www-datawww-datarequire 'yaml' module Kernel # The Kernel method #yaml is a shortcut to YAML::load. # # data = yaml %{ # a: 1 # b: 2 # } # data #=> {"a"=>1, "b"=>2} # def yaml(*args,&blk) YAML.load(*args,&blk) end # As with #to_yaml but removes the header line (i.e. '---') to create # a "YAML fragment". # # CREDT: Thomas Sawyer def to_yamlfrag y = to_yaml y.sub!(/---\ */, '') y end end class File # File.yaml? provides a way to check if a file is a YAML # formatted file: # # File.yaml?('project.yaml') #=> true # File.yaml?('project.xml') #=> false # # Note this isn't perfect. At present it depends on the use # use of an initial document separator (eg. '---'). With # YAML 1.1 the %YAML delaration is supposed to be manditory, # so in the future this can be adapted to fit that standard. def self.yaml?(file) File.open(file) do |f| until f.eof? line = f.gets break true if line =~ /^---/ break false unless line =~ /^(\s*#.*?|\s*)$/ end end end end module YAML # Shortcut for: # # YAML.load(File.new(file)) # def self.read(file) load(File.new(file)) end end facets-2.9.3/lib/standard/facets/argvector.rb0000644000004100000410000001764611714455226021203 0ustar www-datawww-data# = ArgVector # # == Synopsis # # ArgVector provides a very simple means of parsing # command line arguments. # # Unlike other more complex libs this provides only # the most basic and standard parsing functionality. # In many cases that's all one really needs. # # Usage is straight foward. Simply instantiate the # class and query it for the particular "views" of # the command line you want. # # cargs = ArgVector.new("-a foo -b=2") # # cargs.parameters #=> [['foo'],{'a'=>true,'b'=>'2'}] # cargs.flags #=> ['a'] # cargs.preoptions #=> {'a'=>true} # cargs.preflags #=> ['a'] # cargs.subcommand #=> ['foo', [], {'b'=>'2'}] # # == Authors # # * Thomas Sawyer # # == Copying # # Copyright (c) 2006 Thomas Sawyer # # Ruby License # # This module is free software. You may use, modify, and/or # redistribute this software under the same terms as Ruby. # # This program is distributed in the hope that it will be # useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR # PURPOSE. require 'shellwords' # = Argvector # # Argvector provides a very simple means of parsing # command line arguments. # # Unlike other more complex libs this provides only # the most basic and standard parsing functionality. # In many cases that's all one really needs. # # Usage is straight foward. Simply instantiate the # class and query it for the particular "views" of # the command line you want. # # cargs = Argvector.new("-a foo -b=2") # # cargs.parameters #=> [['foo'],{'a'=>true,'b'=>'2'}] # cargs.flags #=> ['a'] # cargs.preoptions #=> {'a'=>true} # cargs.preflags #=> ['a'] # cargs.subcommand #=> ['foo', [], {'b'=>'2'}] # class Argvector def self.parameters(*args) new.parameters(*args) end attr :line attr :argv attr :arity ##attr :opts ##alias :flags :options # Takes the command line string (or array) and options. # Options have flags and end with a hash of option arity. # def initialize(line=nil, arity=nil) @line, @argv = parse_line(line) @arity = parse_arity(arity||{}) parse end public # Returns operand array. def operands @operands end # deprecate alias ? alias arguments operands # Returns options hash. def options @options end # Returns [operands, options], which is good for plugging # directly into a method. def parameters return @operands, @options end # Return flags, which are true options. def flags f = [] @options.each do |k, v| if TrueClass===v or FalseClass===v # not that it's ever false f << k end end return f end # Assumes the first operand is a "subcommand" and # returns it and the argments following it as # parameters. def subcommand_with_parameters opts, args = *parse_preoptions(argv) cmd = args.shift subargs = self.class.new(args, @arity) return [cmd, *subargs.parameters] end alias subcommand subcommand_with_parameters # def subcommand_with_preoptions pre, args = *parse_preoptions(argv) cmd = args.shift subargs = self.class.new(args, @arity) args, opts = *subargs.parameters return [cmd, args, pre.merge(opts)] end # Assumes the first operand is a "subcommand" and # returns it and the argments following it as # another Arguments object. # # TODO: This probably should be called 'subcommand'. # def subcommand_with_arguments opts, args = *parse_preoptions(argv) cmd = args.shift subargs = self.class.new(args, @arity) return cmd, subargs end # Returns a hash of options that occur before # the first operand. This works well with # subcommand to get the main command's options. # # line = "--trace stamp --file VERSION" # cargs = Argvector.new(line) # opts = cargs.preoptions # opts #=> {"trace"=>true} # def preoptions preopts, remainder = *parse_preoptions(argv) return preopts end # Same as +flags+ but only returns flags in the # preoptions. def preflags preopts, remainder = *parse_preoptions(argv) f = [] preopts.each do |k, v| if TrueClass===v or FalseClass===v # not that it's ever false f << k end end return f end # Like parameters but without allowing for duplicate options. def parameters_without_duplicates opts = {} @options.each do |k,v| if Array===v opts[k] = v[0] else opts[k] = v end end return @operands, opts end #private # Basic parser partitions the command line into options and # operands. Options are converted to a hash and the two # parts are returned. # # line = "--trace stamp --file=VERSION" # argv = Argvector.new(line) # # args, keys = *argv.parse # # args #=> ["stamp"] # keys #=> {"trace"=>true, "file"=>"VERSION"} # def parse args = assoc_options(argv) #, *opts_arity) opts, opds = args.partition{ |a| Array === a } @operands = opds @options = format_options(opts) return @operands, @options end # First pass parser to split the command line into an # array using Shellwords, if not already so divided. def parse_line(line=nil) if line case line when String argv = Shellwords.shellwords(line) else argv = line.to_ary.dup line = argv.join(' ') end else argv = ARGV.dup line = argv.join(' ') end return line, argv end ## Ensure opts are a uniform. ## ##def clean_opts( opts ) ## opts2 = opts.collect{ |o| o.to_sym } ## opts2 = opts2 & [:simple, :repeat] # valid options only ## return opts2 ##end # Ensure arity is uniform. def parse_arity(arity) arity2 = {} arity.each{ |k,v| arity2[k.to_s] = v.to_i } return arity2 end # Parse preoptions. A "preoption" is one that # occurs before the first operans (if any). def parse_preoptions(args) ##args = args.dup args = multi_flag(args) #unless opts.include?(:simple) flags = [] while args.first =~ /^-/ key = args.shift key.sub!(/^-{1,2}/,'') if key.index('=') key, val = key.split('=') elsif a = arity[key] val = args.slice!(0,a) val = val.first if a == 1 else val = true end flags << [key, val] end flags = format_options(flags) return flags, args end # Parse flags takes the command line and transforms it such that # flags (eg. -x and --x) are elemental associative arrays. # # line = "--foo hello --try=this" # argv = Argvector.new(line) # # args = line.split(/\s/) # argv.assoc_options(args) #=> [ ["foo",true], "hello", ["try","this"] ] # def assoc_options(args) ##args = args.dup args = multi_flag(args) #unless opts.include?(:simple) i = 0 while i < args.size arg = args[i] case arg when /^-/ arg = arg.sub(/^-{1,2}/,'') if arg.index('=') key, val = arg.split('=') args[i] = [key, val||true] elsif arity.key?(arg) cnt = arity[arg] key = arg val = args[i+1,cnt] args[i,cnt+1] = [[key, *val]] i += (cnt - 1) else key = arg args[i] = [key,true] end end i += 1 end return args end # Split single letter option groupings into separate options. # ie. -xyz => -x -y -z def multi_flag(args=nil) args ||= argv args.collect { |arg| if md = /^-(\w{2,})/.match( arg ) md[1].split(//).collect { |c| "-#{c}" } else arg.dup end }.flatten end # Format flag options. This converts the associative array of # options/flags into a hash. Repeat options will be placed in arrays. def format_options(assoc_options) opts = {} assoc_options.each do |k,v| if opts.key?(k) opts[k] = [opts[k]].flatten << v else opts[k] = v end end return opts end end ArgVector = Argvector facets-2.9.3/lib/standard/facets/tuple.rb0000644000004100000410000001447511714455226020335 0ustar www-datawww-datarequire 'facets/multiton' # = Tuple # # Tuple is essentially an Array, but Comaparable and Immutable. # # A tuple can be made using #new or #[] just as one builds an array, # or using the #to_t method on a string or array. With a string tuple # remembers the first non-alphanumeric character as the tuple divider. # # == Usage # # t1 = Tuple[1,2,3] # t2 = Tuple[2,3,4] # # (t1 < t2) #=> true # (t1 > t2) #=> false # # t1 = '1.2.3'.to_t # t2 = '1-2-3'.to_t # # t1.to_s #=> "1.2.3" # t2.to_s #=> "1.2.3" # # (t1 == t2) #=> true # # Keep in mind that Tuple[1,2,3] is not the same as Tuple['1','2','3']. # #-- # TODO: The #hash method needs a touch-up. # # TODO: There are a few more methods yet to borrow from Array. # Consider how #+, #-, etc. ought to work. #++ class Tuple include ::Multiton include ::Enumerable include ::Comparable def self.multiton_id(arg=0, default=0, &block) if block_given? values = [] arg.times { |i| values << block[i] } elseif Integer === arg values = [ default ] * arg else values = arg.to_ary end values end def initialize(arg=0, default=0, &blk) if block_given? @values = [] arg.times { |i| @values << blk[i] } elseif Integer === arg @values = [ default ] * arg else @values = arg.to_ary end @default = default ##@divider = '.' end attr_accessor :default ##def divider( set=nil ) ## return @divider unless set ## @divider = set ## self ##end protected def values() @values end public SEGMENT_SEPARATOR = '.' def inspect() to_a.inspect end def to_t() self end def to_tuple() self end def to_a() Array(@values) end def to_ary() Array(@values) end def to_s(divider=nil) @values.join(divider || SEGMENT_SEPARATOR) end def size() @values.size end def length() @values.size end def empty?() return true if @values.empty? return true if @values == [ @default ] * @values.size false end def each( &block ) @values.each( &block ) end def each_index( &block ) @values.each_index( &block ) end def [](i) @values.fetch(i,@default) end def []=(i,v) @values[i] = v end def index() @values.index end def rindex() @values.rindex end # Unlike Array, Tuple#<< cannot act in place # becuase Tuple's are immutable. def <<( obj ) self.class.instance( to_a << obj ) end def pop() Tuple.instance( to_a.pop ) end def push( obj ) Tuple.instance( to_a.push(obj) ) end # Pulls a value off the beginning of a tuple. # This method is otherwsie known as #shift. def pull() Tuple.instance( to_a.shift ) end # Stands for "Put On Top". This method is the opposite of #pull and is # otherwise known as #unshift. def pot( obj ) Tuple.instance( to_a.unshift(obj) ) end alias_method :unshift, :pot alias_method :shift, :pull # Returns true if two tuple references are for the # very same tuple. def eql?( other ) return true if object_id == other.object_id ##return true if values.eql? other.values end # def <=>( other ) other = other.to_t [size, other.size].max.times do |i| c = self[i] <=> other[i] return c if c != 0 end 0 end # For pessimistic constraint (like '~>' in gems) def =~( other ) other = other.to_t upver = other.dup upver[0] += 1 self >= other and self < upver end def first() @values.first end def last() @values.last end # These are useful for using a Tuple as a version. def major() @values.first end def minor() @values.at(1) end def teeny() @values.at(2) end # Unique hash value. def hash # TODO: This needs to take into account the default # and maybe the divider too. to_a.hash end # class-level ----------------------------------------------- class << self # def []( *args ) instance( args ) end # Translates a string in the form on a set of numerical and/or # alphanumerical characters separated by non-word characters (eg \W+) # into a Tuple. The values of the tuple will be converted to integers # if they are purely numerical. # # Tuple.cast_from_string('1.2.3a') #=> [1,2,"3a"] # # It you would like to control the interpretation of each value # as it is added to the tuple you can supply a block. # # Tuple.cast_from_string('1.2.3a'){ |v| v.upcase } #=> ["1","2","3A"] # # This method is called by String#to_t. def cast_from_string( str, &yld ) args = str.to_s.split(/\W+/) div = /\W+/.match( str.to_s )[0] if block_given? args = args.collect{ |a| yld[a] } else args = args.collect { |i| /^[0-9]+$/ =~ i ? i.to_i : i } end self.instance(args) #.divider( div ) end # def cast_from_array( arr ) self.instance( arr ) end # Parses a constraint returning the operation as a lambda. def constraint_to_lambda( constraint, &yld ) op, val = *parse_constraint( constraint, &yld ) lambda { |t| t.send(op, val) } end # def parse_constraint( constraint, &yld ) constraint = constraint.strip re = %r{^(=~|~>|<=|>=|==|=|<|>)?\s*(\d+(:?[-.]\d+)*)$} if md = re.match( constraint ) if op = md[1] op = '=~' if op == '~>' op = '==' if op == '=' val = cast_from_string( md[2], &yld ) #instance( md[2] ) else op = '==' val = cast_from_string( constraint, &yld ) #instance( constraint ) end else raise ArgumentError, "invalid constraint" end return op, val end end end class ::String # Translates a string in the form on a set of numerical and/or # alphanumerical characters separated by non-word characters (eg \W+) # into a Tuple. The values of the tuple will be converted to integers # if they are purely numerical. # # '1.2.3a'.to_t #=> [1,2,"3a"] # # It you would like to control the interpretation of each value # as it is added to the tuple you can supply a block. # # '1.2.3a'.to_t { |v| v.upcase } #=> ["1","2","3A"] # # This method calls Tuple.cast_from_string. def to_t( &yld ) Tuple.cast_from_string( self, &yld ) end end class ::Array # Convert an array into a tuple. def to_t Tuple.cast_from_array( self ) end end # Copyright (c) 2005 Thomas Sawyer (Ruby License) facets-2.9.3/lib/standard/facets/zlib.rb0000644000004100000410000000137611714455226020140 0ustar www-datawww-data# A convenient wrapper for the zlib standard library that allows # compression/decompression of strings with gzip. module Zlib ##class Stream < StringIO ## def close; rewind; end ##end # Decompresses a gzipped string. def self.decompress(source) GzipReader.new(StringIO.new(source)).read end # Compresses a string using gzip. def self.compress(source) output = StringIO.new class << output def close; rewind; end end gz = GzipWriter.new(output) gz.write(source) gz.close output.string end # Inflate a deflated sting. def self.inflate(string) Inflate.inflate(string) end # Deflate a string. def self.deflate(string, level=DEFAULT_COMPRESSION) Deflate.deflate(string, level) end end facets-2.9.3/lib/standard/facets/fileutils/0000755000004100000410000000000011714455226020644 5ustar www-datawww-datafacets-2.9.3/lib/standard/facets/fileutils/which.rb0000644000004100000410000000323111714455226022272 0ustar www-datawww-datarequire 'fileutils' module FileUtils if const_defined?(:Win32Exts) Win32Exts.concat %w{.exe .com .bat .cmd} Win32Exts.uniq! else Win32Exts = %w{.exe .com .bat .cmd} end module_function # Looks for the first occurrence of _program_ within _path_. # # On the MS Windows platform, it looks for executables ending with .exe, # .bat and .com, which you may optionally include in the program name. # Returns nil if not found. # # CREDIT: Daniel J. Berger, Michael Granger # #-- # The which() method was adopted from Daniel J. Berger, via PTools # which in in turn was adopted fromt the FileWhich code posted by # Michael Granger on http://www.rubygarden.org. #++ def which(prog, path=ENV['PATH']) path.split(File::PATH_SEPARATOR).each {|dir| # Windows checks against specific extensions if File::ALT_SEPARATOR ext = Win32Exts.find{|ext| if prog.include?('.') # Assume extension already included f = File.join(dir,prog) else f = File.join(dir,prog+ext) end File.executable?(f) && !File.directory?(f) } if ext # Use backslashes, not forward slashes if prog.include?('.') # Assume extension already included f = File.join( dir, prog ).gsub(/\//,'\\') else f = File.join( dir, prog + ext ).gsub(/\//,'\\') end return f end else f = File.join(dir,prog) # Avoid /usr/lib/ruby, for example if File.executable?(f) && !File.directory?(f) return File::join( dir, prog ) end end } nil end end facets-2.9.3/lib/standard/facets/fileutils/cp_rx.rb0000644000004100000410000000310711714455226022305 0ustar www-datawww-datamodule FileUtils module_function # Both of these are modified from the implementations in fileutils.rb from Ruby 1.9.1p378. # Like FileUtils.cp_r, but takes a filter proc that can return false to skip a file: # # cp_rx "bigDirectoryTree", "dest", {:noop => true} do |name| # /dontCopyThis$/.match(name) # end # # Note that if the filter rejects a subdirectory then everything within that # subdirectory is automatically skipped as well. def cp_rx(src, dest, options = {}, &filter) fu_check_options(options, OPT_TABLE['cp_r']) if options[:verbose] fu_output_message("cp -r#{options[:preserve] ? 'p' : ''}#{options[:remove_destination] ? ' --remove-destination' : ''} #{[src,dest].flatten.join ' '}") end return if options[:noop] fu_each_src_dest(src, dest) do |s, d| copy_entryx(s, d, filter, options[:preserve], options[:dereference_root], options[:remove_destination]) end end # Like FileUtils.copy_entry, but takes a filter proc that can return false to skip a file. # # Note that if the filter rejects a subdirectory then everything within that # subdirectory is automatically skipped as well. def copy_entryx(src, dest, filter, preserve = false, dereference_root = false, remove_destination = false) Entry_.new(src, nil, dereference_root).traverse do |ent| if filter.call(ent.path) then destent = Entry_.new(dest, ent.rel, false) File.unlink destent.path if remove_destination && File.file?(destent.path) ent.copy destent.path ent.copy_metadata(destent.path) if preserve end end end end facets-2.9.3/lib/standard/facets/fileutils/whereis.rb0000644000004100000410000000354211714455226022643 0ustar www-datawww-datarequire 'fileutils' module FileUtils if const_defined?(:Win32Exts) Win32Exts.concat %w{.exe .com .bat .cmd} Win32Exts.uniq! else Win32Exts = %w{.exe .com .bat .cmd} end module_function # In block form, yields each ((*program*)) within ((*path*)). In non-block # form, returns an array of each ((*program*)) within ((*path*)). Returns # (({nil})) if not found. # # On the MS Windows platform, it looks for executables ending with .exe, # .bat and .com, which you may optionally include in the program name: # # FileUtils.whereis("ruby") #=> ['/usr/local/bin/ruby','/opt/bin/ruby'] # # CREDIT: Daniel J. Berger def whereis(prog, path=ENV['PATH']) #:yield: dirs = [] path.split(File::PATH_SEPARATOR).each{|dir| # Windows checks against specific extensions if File::ALT_SEPARATOR if prog.include?('.') f = File.join(dir,prog) if File.executable?(f) && !File.directory?(f) if block_given? yield f.gsub(/\//,'\\') else dirs << f.gsub(/\//,'\\') end end else Win32Exts.find_all{|ext| f = File.join(dir,prog+ext) if File.executable?(f) && !File.directory?(f) if block_given? yield f.gsub(/\//,'\\') else dirs << f.gsub(/\//,'\\') end end } end else f = File.join(dir,prog) # Avoid /usr/lib/ruby, for example if File.executable?(f) && !File.directory?(f) if block_given? yield f else dirs << f end end end } dirs.empty? ? nil : dirs end end facets-2.9.3/lib/standard/facets/fileutils/wc.rb0000644000004100000410000000271611714455226021610 0ustar www-datawww-datarequire 'fileutils' module FileUtils module_function # With no arguments, returns a four element array consisting of the number # of bytes, characters, words and lines in _filename_, respectively. # # Valid options are +bytes+, +characters+ (or just 'chars'), # +words+ and +lines+: # # # Return the number of words in 'myfile' # FileUtils.wc("myfile",'words') # # CREDIT: Daniel J. Berger def wc(filename,option='all') option.downcase! valid = %w/all bytes characters chars lines words/ unless valid.include?(option) raise "Invalid option: '#{option}'" end n = 0 if option == 'lines' IO.foreach(filename){ n += 1 } return n elsif option == 'bytes' File.open(filename){ |f| f.each_byte{ n += 1 } } return n elsif option == 'characters' || option == 'chars' File.open(filename){ |f| while f.getc n += 1 end } return n elsif option == 'words' IO.foreach(filename){ |line| n += line.split.length } return n else bytes,chars,lines,words = 0,0,0,0 IO.foreach(filename){ |line| lines += 1 words += line.split.length chars += line.split('').length } File.open(filename){ |f| while f.getc bytes += 1 end } return [bytes,chars,words,lines] end end end facets-2.9.3/lib/standard/facets/fileutils/head.rb0000644000004100000410000000004111714455226022065 0ustar www-datawww-datarequire 'facets/fileutils/slice' facets-2.9.3/lib/standard/facets/fileutils/amass.rb0000644000004100000410000000227011714455226022276 0ustar www-datawww-datamodule FileUtils module_function # An intergrated glob like method that takes a set of include globs, # exclude globs and ignore globs to produce a collection of paths. # # The ignore_globs differ from exclude_globs in that they match by # the basename of the path rather than the whole pathname. # # TODO: Should ignore be based on any portion of the path, not just the basename? # def amass(include_globs, exclude_globs=[], ignore=[]) include_files = [include_globs].flatten.map{ |g| Dir.glob(g) }.flatten.uniq exclude_files = [exclude_globs].flatten.map{ |g| Dir.glob(g) }.flatten.uniq include_files = include_files.map{ |f| File.directory?(f) ? File.join(f, '**/*') : f } # Recursive! exclude_files = exclude_files.map{ |f| File.directory?(f) ? File.join(f, '**/*') : f } # Recursive! include_files = include_files.flatten.map{ |g| Dir.glob(g) }.flatten.uniq exclude_files = exclude_files.flatten.map{ |g| Dir.glob(g) }.flatten.uniq files = include_files - exclude_files files = files.reject{ |f| [ignore].flatten.any?{ |x| File.fnmatch?(x, File.basename(f)) } } files end # Make public (for all submodules too). public :amass end facets-2.9.3/lib/standard/facets/fileutils/ln_r.rb0000644000004100000410000000702411714455226022126 0ustar www-datawww-datamodule FileUtils unless method_defined?(:ln_r) # # Options: noop verbose dereference_root remove_destination # # Hard link +src+ to +dest+. If +src+ is a directory, this method links # all its contents recursively. If +dest+ is a directory, links # +src+ to +dest/src+. # # +src+ can be a list of files. # # # Installing ruby library "mylib" under the site_ruby # FileUtils.rm_r site_ruby + '/mylib', :force # FileUtils.ln_r 'lib/', site_ruby + '/mylib' # # # Examples of copying several files to target directory. # FileUtils.ln_r %w(mail.rb field.rb debug/), site_ruby + '/tmail' # FileUtils.ln_r Dir.glob('*.rb'), '/home/aamine/lib/ruby', :noop => true, :verbose => true # # # If you want to copy all contents of a directory instead of the # # directory itself, c.f. src/x -> dest/x, src/y -> dest/y, # # use following code. # FileUtils.ln_r 'src/.', 'dest' # cp_r('src', 'dest') makes src/dest, # # but this doesn't. # # TODO: Why --remove-destination and not just --force? def ln_r(src, dest, options = {}) fu_check_options options, OPT_TABLE['ln_r'] fu_output_message "ln -r#{options[:remove_destination] ? ' --remove-destination' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose] return if options[:noop] options = options.dup options[:dereference_root] = true unless options.key?(:dereference_root) fu_each_src_dest(src, dest) do |s, d| link_entry s, d, options[:dereference_root], options[:remove_destination] end end module_function :ln_r OPT_TABLE = {} unless const_defined?(:OPT_TABLE) OPT_TABLE['ln_r'] = [:noop, :verbose, :dereference_root, :remove_destination] # # Hard links a file system entry +src+ to +dest+. # If +src+ is a directory, this method links its contents recursively. # # Both of +src+ and +dest+ must be a path name. # +src+ must exist, +dest+ must not exist. # # If +dereference_root+ is true, this method dereference tree root. # # If +remove_destination+ is true, this method removes each destination file before copy. # def link_entry(src, dest, dereference_root = false, remove_destination = false) Entry_.new(src, nil, dereference_root).traverse do |ent| destent = Entry_.new(dest, ent.rel, false) File.unlink destent.path if remove_destination && File.file?(destent.path) ent.link destent.path end end module_function :link_entry class Entry_ #:nodoc: def link(dest) case when directory? if !File.exist?(dest) and descendant_diretory?(dest, path) raise ArgumentError, "cannot link directory %s to itself %s" % [path, dest] end begin Dir.mkdir dest rescue raise unless File.directory?(dest) end else file? File.link path(), dest end end unless const_defined?(:DIRECTORY_TERM) if File::ALT_SEPARATOR DIRECTORY_TERM = "(?=[/#{Regexp.quote(File::ALT_SEPARATOR)}]|\\z)".freeze else DIRECTORY_TERM = "(?=/|\\z)".freeze end SYSCASE = File::FNM_SYSCASE.nonzero? ? "-i" : "" end unless method_defined?(:descendant_diretory?) def descendant_diretory?(descendant, ascendant) /\A(?#{SYSCASE}:#{Regexp.quote(ascendant)})#{DIRECTORY_TERM}/ =~ File.dirname(descendant) end end end end end facets-2.9.3/lib/standard/facets/fileutils/safe_ln.rb0000644000004100000410000000065111714455226022602 0ustar www-datawww-datarequire 'fileutils' module FileUtils module_function LINKING_SUPPORTED = [true] # Attempt to do a normal file link, but fall back # to a copy if the link fails. # # CREDIT: Jim Weirich def safe_ln(*args) unless LINKING_SUPPORTED[0] cp(*args) else begin ln(*args) rescue Errno::EOPNOTSUPP LINKING_SUPPORTED[0] = false cp(*args) end end end end facets-2.9.3/lib/standard/facets/fileutils/tail.rb0000644000004100000410000000004111714455226022115 0ustar www-datawww-datarequire 'facets/fileutils/slice' facets-2.9.3/lib/standard/facets/fileutils/outofdate.rb0000644000004100000410000000177711714455226023177 0ustar www-datawww-datarequire 'fileutils' module FileUtils module_function # The opposite of #uptodate? def outofdate?(path, *sources) #return true unless File.exist?(path) ! uptodate?(path, sources.flatten) end # Alias for #outofdate? alias_method :out_of_date?, :outofdate? # Alias for #uptodate? alias_method :up_to_date?, :uptodate? # # TODO: Does a path need updating, based on given +sources+? # # This compares mtimes of give paths. Returns false # # if the path needs to be updated. # # # # DEPRECATE: Is this in any way better than `! uptodate?` ? # def out_of_date?(path, *sources) # return true unless File.exist?(path) # # sources = sources.collect{ |source| Dir.glob(source) }.flatten # mtimes = sources.collect{ |file| File.mtime(file) } # # return true if mtimes.empty? # TODO: This the way to go here? # # File.mtime(path) < mtimes.max # end # Make public (for all submodules too). public :outofdate? public :out_of_date? public :up_to_date? end facets-2.9.3/lib/standard/facets/fileutils/stage.rb0000644000004100000410000000354711714455226022305 0ustar www-datawww-datarequire 'fileutils' module FileUtils module_function # Stage by hard linking included files to a stage directory. # # stage_directory - Where to stage the files # source_directory - Where to find files to stage # files - Files to link in stage relative to source # # TODO: Rename to #link_stage or something less likely to name clash? # TODO: Add options for :verbose, :noop and :dryrun ? # def stage(stage_directory, source_directory, files, options={}) return stage_directory if options[:noop] || options[:dryrun] stage_directory, source_directory = stage_directory.to_s, source_directory.to_s ## ensure existance of staging area rm_r(stage_directory) if File.directory?(stage_directory) mkdir_p(stage_directory) ## link files into staging area files.each do |f| src = File.join(source_directory, f) file = File.join(stage_directory, f) if File.directory?(src) mkdir_p(file) unless File.exist?(file) else fdir = File.dirname(file) mkdir_p(fdir) unless File.exist?(fdir) unless File.exist?(file) and File.mtime(file) >= File.mtime(src) ln(src, file) #safe_ln ? end end end return stage_directory end # Make public (for all submodules too). public :stage module NoWrite module_function def stage(stage_directory, files, options={}) options[:noop] = true FileUtils.stage(stage_directory, files, options={}) end end module Verbose module_function def stage(stage_directory, files, options={}) options[:verbose] = true FileUtils.stage(stage_directory, files, options={}) end end module DryRun module_function def stage(stage_directory, files, options={}) options[:dryrun] = true FileUtils.stage(stage_directory, files, options={}) end end end facets-2.9.3/lib/standard/facets/fileutils/slice.rb0000644000004100000410000000262211714455226022272 0ustar www-datawww-datarequire 'fileutils' module FileUtils module_function # In block form, yields lines +from+-+to+. In non-block form, returns # an array of lines +from+-+to+: # # # Returns lines 8-12 of 'myfile' # FileUtils.body("myfile",8,12) # # CREDIT Shashank Date, via Daniel Berger. def slice(filename,from,to) #:yield: IO.readlines(filename)[from-1..to-1] end # In block form, yields the first number of +lines+ of file +filename+. # In non-block form, it returns an array of the first number of +lines+: # # # Returns first 10 lines of 'myfile' # FileUtils.head("myfile", 10) # def head(filename,lines) #:yield: a = [] IO.foreach(filename){|line| break if lines <= 0 lines -= 1 if block_given? yield line else a << line end } return a.empty? ? nil : a end # In block form, yields the last number of +lines+ of file +filename+. # In non-block form, it returns the lines as an array. # # Note that this method slurps the entire file, so I don't recommend it # for very large files. If you want an advanced form of +tail+, I # suggest using file-tail, by Florian Frank (available on the RAA): # # # Returns last 3 lines of 'myfile' # FileUtils.tail("myfile",3) # # And no tail -f. def tail(filename,lines) #:yield IO.readlines(filename).reverse[0..lines-1].reverse end end facets-2.9.3/lib/standard/facets/shellwords.rb0000644000004100000410000000463011714455226021362 0ustar www-datawww-datarequire 'shellwords' module Shellwords module_function # Escape special characters used in most unix shells # to use it, eg. with system(). # # This differs from Ruby's #escape in that it does not # escape shell variables, e.g. $0. def alt_escape(cmdline) cmdline.gsub(/([\\\t\| &`<>)('"])/) { |s| '\\' << s } end unless method_defined?(:escape) def escape(cmdline) cmdline.gsub(/([\\\t\| &`<>)('"])/) { |s| '\\' << s } end end # Escape special character used in DOS-based shells. # # TODO: How to integrate with rest of system? # 1. Use platform condition? # 2. Use separate dos_xxx methods? # 3. Put in separate PowerShellwords module? # # CREDIT: Lavir the Whiolet def dos_escape(cmdline) '"' + cmdline.gsub(/\\(?=\\*\")/, "\\\\\\").gsub(/\"/, "\\\"").gsub(/\\$/, "\\\\\\").gsub("%", "%%") + '"' end # The coolest little arguments parser in all of Rubyland. # # CREDIT: Michel Martens def run(argv, opts) argv = (String === argv ? shellwords(argv) : argv.to_a.dup) args = [] while argv.any? item = argv.shift flag = opts[item] if flag # Work around lambda semantics in 1.8.7. arity = [flag.arity, 0].max # Raise if there are not enough parameters # available for the flag. if argv.size < arity raise ArgumentError end # Call the lambda with N items from argv, # where N is the lambda's arity. flag.call(*argv.shift(arity)) else # Collect the items that don't correspond to # flags. args << item end end args end end class Array # Convert an array into command line parameters. # The array is accepted in the format of Ruby # method arguments --ie. [arg1, arg2, ..., hash] # def shellwords opts, args = *flatten.partition{ |e| Hash === e } opts = opts.inject({}){ |m,h| m.update(h); m } opts.shellwords + args end # def shelljoin Shellwords.shelljoin(shellwords) end end class Hash # def shellwords argv = [] each do |f,v| m = f.to_s.size == 1 ? '-' : '--' case v when false, nil when Array v.each do |e| argv << %[#{m}#{f}="#{e}"] end when true argv << %[#{m}#{f}] else argv << %[#{m}#{f}="#{v}"] end end argv end # def shelljoin shellwords.shelljoin end end facets-2.9.3/lib/standard/facets/interval.rb0000644000004100000410000002151511714455226021021 0ustar www-datawww-datarequire 'facets/multiton' require 'facets/enumargs' #require 'facets/infinity' # TODO: Tie in Infinity with Interval. # While Ruby support the Range class out of the box, is does not quite # fullfil the role od a real Interval class. For instance, it does # not support excluding the front sentinel. This is because Range also # tries to do triple duty as a simple sequence and as a simple tuple-pair, # thus limiting its potential as an Interval. The Interval class remedies # the situation by commiting to interval behavior, and then extends the class' # capabilites beyond that of the standard Range in ways that naturally # fall out of that. # # Range depends on two methods: #succ and #<=>. If numeric ranges were the # only concern, those could just as well be #+ and #<=>, but esoteric forms # make that unfeasible --the obvious example being a String range. But a # proper Interval class requires mathematical continuation, thus the Interval # depends on #+ and #<=>, as well as #- as the inverse of #+. # # i = Interval.new(1,5) # i.to_a #=> [1,2,3,4,5] # # i = Interval[0,5] # i..step(2).to_a #=> [0,2,4] # # i = Interval[1,5] # i.step(-1).to_a #=> [5,4,3,2,1] # # i = Interval[1,3] # i.step(1,2).to_a #=> [1.0,1.5,2.0,2.5,3.0] # class Interval include Multiton include Enumerable::Arguments # def self.[]( *args ) self.new( *args ) end # def initialize(first, last, exclude_first=false, exclude_last=false ) raise ArgumentError, "bad value for interval" if first.class != last.class @first = first @last = last @exclude_first = exclude_first @exclude_last = exclude_last @direction = (@last <=> @first) end # Returns a two element array of first and last sentinels. # # (0..10).sentinels #=> [0,10] # def sentinels return [@first, @last] end # Returns the first or last sentinal of the interval. def first ; @first ; end def last ; @last ; end # def exclude_first? ; @exclude_first ; end def exclude_last? ; @exclude_last ; end # (IMHO) these should be deprectated alias_method( :begin, :first ) alias_method( :end, :last ) alias_method( :exclude_begin?, :exclude_first? ) alias_method( :exclude_end?, :exclude_last? ) # Returns +true+ if the start and end sentinels are equal and the interval is closed; otherwise +false+. def degenerate? ; @direction == 0 and ! (@exclusive_first or @exclusive_last) ; end # Returns +true+ if the start and end sentinels are equal and the interval is open; otherwise +false+. def null? ; @direction == 0 and @exclusive_first and @exclusive_last ; end # Returns the direction of the interval indicated by +1, 0 or -1. # # (1..5).direction #=> 1 # (5..1).direction #=> -1 # (1..1).direction #=> 0 # def direction ; @direction ; end # Returns a new interval inclusive of of both sentinels. def closed; Interval.new(@first, @last, true, true) ; end # Returns a new interval exclusive of both sentinels. def opened; Interval.new(@first, @last, true, true) ; end # Returns a new interval with either the first or the last sentinel exclusive. # If the parameter is false, the deafult, then the first sentinel is excluded; # if the parameter is true, the last sentinel is excluded. def half_closed(e=false) e ? Interval.new(@first, @last, true, false) : Interval.new(@first, @last, false, true) end # Returns a new interval with one of the two sentinels opened or closed def first_closed ; Interval.new(@first, @last, false, true) ; end def last_closed ; Interval.new(@first, @last, true, false) ; end def first_opened ; Interval.new(@first, @last, true, false) ; end def last_opened ; Interval.new(@first, @last, false, true) ; end # Unary shorthands. These return a new interval exclusive of first, # last or both sentinels, repectively. def +@ ; Interval.new(first, last, true, false) ; end def -@ ; Interval.new(first, last, false, true) ; end def ~@ ; Interval.new(first, last, true, true) ; end # Returns a new interval with the sentinels reversed. # # (0..10).reversed #=> 10..0 # def reversed Interval.new(@last, @first, true, true) end # Returns the length of the interval as the difference between # the first and last elements. Returns +nil+ if the sentinal objects # do not support distance comparison (#distance). # # TODO: Add +n+ parameter to count segmentations like those produced by #each. def distance @last - @first #if @last.respond_to?( :distance ) # @last.distance( @first ) #else # #self.to_a.length #end end alias_method( :length, :distance ) alias_method( :size, :distance ) # Returns the lesser of the first and last sentinals. def min ((@first <=> @last) == -1) ? @first : @last end # Returns the greater of the first and last sentinals. def max ((@first <=> @last) == 1) ? @first : @last end # Returns true or false if the element is part of the interval. def include?(x) # todo: infinity? tf = exclude_first? ? 1 : 0 tl = exclude_last? ? -1 : 0 (x <=> first) >= tf and (x <=> last) <= tl end alias_method( :===, :include? ) alias_method( :member?, :include? ) =begin # def include?(x) # tf = exclude_first? ? 1 : 0 # tl = exclude_last? ? -1 : 0 # # if other classes handled Infinity in their <=> method # # (which probably they should) this clause would not be required # if first.kind_of?(InfinityClass) # ft = ((first <=> x) <= tf) # else # ft = (x <=> first) >= tf # end # if last.kind_of?(InfinityClass) # fl = ((last <=> x) >= tl) # else # fl = (x <=> last) <= tl # end # ft && fl # end =end # Iterates over the interval, passing each _n_th element to the block. # If n is not given then n defaults to 1. Each _n_th step is determined # by invoking +\++ or +\-+ n, depending on the direction of the interval. # If n is negative the iteration is preformed in reverse form end sentinal # to front sentinal. A second parameter, d, can be given in which case # the applied step is calculated as a fraction of the interval's length # times n / d. This allows iteration over the whole interval in equal sized # segments. # # 1..5.each { |e| ... } #=> 1 2 3 4 5 # 1..5.each(2) { |e| ... } #=> 1 3 5 # 1..5.each(1,2) { |e| ... } #=> 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 # # @todo Deprecate arguments and simplify each definition accordingly. def each(n=nil, d=nil) # :yield: if n warn "FACETS: `interval.each(n,d){...}` will be deprecated.\n" + "Use `interval.step(n,d).each{...}` instead." else n = 1 end return (n < 0 ? @last : @first) if degenerate? # is this right for all values of n ? s = d ? self.length.to_f * (n.to_f / d.to_f) : n.abs raise "Cannot iterate over zero length steps." if s == 0 s = s * @direction if n < 0 e = @exclude_last ? @last - s : @last #e = @exclude_last ? @last.pred(s) : @last t = @exclude_last ? 1 : 0 #while e.cmp(@first) >= t while (e <=> @first) >= t yield(e) e -= s #e = e.pred(s) end else e = @exclude_first ? @first + s : @first #e = @exclude_first ? @first.succ(s) : @first t = @exclude_last ? -1 : 0 #while e.cmp(@last) <= t while (e <=> @last) <= t yield(e) e += s #e = e.succ(s) end end end # def step(n=1, d=nil) # :yield: return (n < 0 ? @last : @first) if degenerate? # is this right for all values of n ? if block_given? s = d ? self.length.to_f * (n.to_f / d.to_f) : n.abs raise "Cannot iterate over zero length steps." if s == 0 s = s * @direction if n < 0 e = @exclude_last ? @last - s : @last #e = @exclude_last ? @last.pred(s) : @last t = @exclude_last ? 1 : 0 #while e.cmp(@first) >= t while (e <=> @first) >= t yield(e) e -= s #e = e.pred(s) end else e = @exclude_first ? @first + s : @first #e = @exclude_first ? @first.succ(s) : @first t = @exclude_last ? -1 : 0 #while e.cmp(@last) <= t while (e <=> @last) <= t yield(e) e += s #e = e.succ(s) end end else Enumerator.new(self, :step, n, d) end end # Should there be a #reverse_each ? # Since #each can now take a negative argument, this isn't really needed. # Should it exist anyway and routed to #each? # Also, alias_method( :reverse_step, :reverse_each ) # Compares two intervals to see if they are equal def eql?(other) return false unless @first == other.first return false unless @last == other.last return false unless @exclude_first == other.exclude_first? return false unless @exclude_last == other.exclude_last? true end end facets-2.9.3/lib/standard/facets/digest.rb0000644000004100000410000000011311714455226020443 0ustar www-datawww-datarequire 'facets/digest/base64digest' require 'facets/digest/salted_digest' facets-2.9.3/lib/standard/facets/pathname.rb0000644000004100000410000001352511714455226020774 0ustar www-datawww-data# = Pathname # # Ruby's standard Pathname class with extensions. # # == Authors: # # * Daniel Burger # * Thomas Sawyer # # == Copying # # Copyright (c) 2006 Thomas Sawyer, Daniel Burger # # Ruby License # # This module is free software. You may use, modify, and/or redistribute this # software under the same terms as Ruby. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. require 'pathname' require 'facets/file/rootname' require 'facets/fileutils/outofdate' class Pathname # Alias #to_s to #to_str when #to_str is not defined. # alias_method(:to_str, :to_s) unless method_defined?(:to_str) # Alternate to Pathname#new. # # Pathname['/usr/share'] # def self.[](path) new(path) end # Start a path. Another alias for #new. # # Pathname / 'usr' # def self./(path) new(path) end # Root constant for building paths from root directory onward. def self.root Pathname.new('/') end # Home constant for building paths from root directory onward. # # TODO: Pathname#home needs to be more robust. # def self.home Pathname.new('~') end # Work constant for building paths from root directory onward. # def self.work Pathname.new('.') end # Platform dependent null device. # # CREDIT Daniel Burger def self.null case RUBY_PLATFORM when /mswin/i 'NUL' when /amiga/i 'NIL:' when /openvms/i 'NL:' else '/dev/null' end end # Try to get this into standard Pathname class. alias_method :/, :+ # def rootname self.class.new(File.rootname(to_s)) end # def split_root head, tail = *::File.split_root(to_s) [self.class.new(head), self.class.new(tail)] end # Glob pathnames. def glob(match, *opts) flags = glob_flags(opts) Dir.glob(::File.join(self.to_s, match), flags).collect{ |m| self.class.new(m) } end # Return the first glob match. # # DEPRECATE: While slightly faster then glob().first, not really worth it # unless this can be rewritten to shortcut on first match (using fnmatch?). # In wich case, is there a better name for this method? def glob_first(match, *opts) flags = glob_flags(opts) file = ::Dir.glob(::File.join(self.to_s, match), flags).first file ? self.class.new(file) : nil end # Return globbed matches with pathnames relative to the current pathname. def glob_relative(match, *opts) flags = glob_flags(opts) files = Dir.glob(::File.join(self.to_s, match), flags) files = files.map{ |f| f.sub(self.to_s.chomp('/') + '/', '') } files.collect{ |m| self.class.new(m) } end private def glob_flags(opts) flags = 0 opts.each do |opt| case opt when Symbol, String flags += ::File.const_get("FNM_#{opt}".upcase) else flags += opt end end flags end public # def empty? Dir.glob(::File.join(to_s, '*')).empty? end # def uptodate?(*sources) ::FileUtils.uptodate?(to_s, sources.flatten) end # def outofdate?(*sources) ::FileUtils.outofdate?(to_s, sources.flatten) end # Recursively visit a directory located by its path, yielding each resource # as its full matching pathname object. If called on a file, yield the file. # # call-seq: # visit => yield each file # visit(all: true) => yield visited directories as well # visit(hidden: true) => yield hidden files and directories as well # # Example use case: # # # Locate any file but *.haml within app/**/* # Pathname.new("app").visit do |f| # next unless f.to_s =~ /\.haml$/ # f # end # # TODO: Use #map instead of #each ? # # CREDIT: Jean-Denis Vauguet def visit(options = {:all => false, :hidden => false}) if self.directory? children.each do |entry| next if entry.basename.to_s[0] == "." && !options[:hidden] yield(entry) unless entry.directory? && !options[:all] ##entry.visit(:all => options[:all]) { |sub_entry| yield sub_entry } if entry.directory? entry.visit(:all => options[:all], :hidden => options[:hidden]) do |sub_entry| yield(sub_entry) end if entry.directory? end else yield self end end ## # Already included in 1.8.4+ version of Ruby (except for inclusion flag) ## if not instance_methods.include?(:ascend) ## ## # Calls the _block_ for every successive parent directory of the ## # directory path until the root (absolute path) or +.+ (relative path) ## # is reached. ## def ascend(inclusive=false,&block) # :yield: ## cur_dir = self ## yield( cur_dir.cleanpath ) if inclusive ## until cur_dir.root? or cur_dir == Pathname.new(".") ## cur_dir = cur_dir.parent ## yield cur_dir ## end ## end ## ## end ## ## # Already included in 1.8.4+ version of Ruby ## if ! instance_methods.include?(:descend) ## ## # Calls the _block_ for every successive subdirectory of the ## # directory path from the root (absolute path) until +.+ ## # (relative path) is reached. ## def descend() ## @path.scan(%r{[^/]*/?})[0...-1].inject('') do |path, dir| ## yield Pathname.new(path << dir) ## path ## end ## end ## ## end # Does a directory contain a matching entry? # Or if the pathname is a file, same as #fnmatch. def include?(pattern,*opts) if directory? glob_first(pattern,*opts) else fnmatch(pattern,*opts) end end end class NilClass # Provide platform dependent null path. # # @standard # require 'facets/pathname' # # @author Daniel Burger def to_path Pathname.null end end class Array # Convert array to Pathname instance. # # @standard # require 'facets/pathname' # def to_path Pathname.new(join('/')) end end facets-2.9.3/lib/standard/facets/find.rb0000644000004100000410000000120311714455226020105 0ustar www-datawww-datarequire 'facets/enumerator' module Find # Identical to find except select returns the matching files as an array. # (find returns nil, which is not very useful if you actually wanted an array.) # Calls the associated block with the name of every file and directory listed # as arguments, then recursively on their subdirectories, and so on. # Return a true (non-false) value from the block for every path that # you want to be returned in the resulting array. You can still use Find.prune. # # CREDIT: Tyler Rick def self.select(*paths, &block) Enumerator.new(self, :find, *paths).select{|value| yield value} end end facets-2.9.3/lib/standard/facets/thread.rb0000644000004100000410000000340711714455226020444 0ustar www-datawww-data# = Thread Related Extensions # # This a small colleciton of thread-related extensions. require 'thread' require 'facets/binding/eval' require 'facets/kernel/__method__' # This is the non-threaded form of #threaded_map_send. require 'facets/enumerable/map_send' module Kernel $MEMO_MUTEX = Mutex.new $MEMO ||= {} # Thead-safe instance-level memoization. # # class MemoExample # attr_accessor :a # def m # safe_memo{ @a } # end # end # # ex = MemoExample.new # # ex.a = 10 # ex.m #=> 10 # # ex.a = 20 # ex.m #=> 10 # def safe_memo(*args, &block) if args.empty? args = block.binding.eval('[self, __method__]') end $MEMO_MUTEX.synchronize do if $MEMO.key?(args) $MEMO[args] else $MEMO[args] = block.call end end end end module Enumerable # Like Enumerable#map but each iteration is processed via # a separate thread. # # CREDIT: Sean O'Halpin def threaded_map #:yield: map{ |e| Thread.new(e){ |t| yield(t) } }.map{ |t| t.value } end # Like Enumerable#map_send but each iteration is processed via # a separate thread. # # CREDIT: Sean O'Halpin def threaded_map_send(meth, *args, &block) map{ |e| Thread.new(e){ |t| t.send(meth, *args, &block) } }.map{ |t| t.value } end end module Kernel private # CREDIT: Zucker def sandbox(rescueblock_or_default=nil) #:yield: Thread.start do $SAFE = 4 yield end.value rescue SecurityError => e if !rescueblock_or_default.nil? if rescueblock_or_default.is_a? Proc rescueblock_or_default.call e else rescueblock_or_default end else raise e end end end # Copyright (c) 2006 Sean O'Halpin, Thomas Sawyer facets-2.9.3/lib/standard/facets/continuation.rb0000644000004100000410000000415711714455226021712 0ustar www-datawww-dataif defined?(Continuation) # = Continuation Extension # # Creates a continuation in a way that is easier to use than callcc. # On the initial call this will return the created Continuation and # the arguments you gave to Continuation.create in an Array. If you # then issue .call() on the Continuation execution will jump back to # the point of time where you initially invoked Continuation.create, # but this time it will return the Continuation and the arguments # you supplied in an Array. # # You can supply a block instead of default arguments which will # cause that block to be executed once and its result to be returned # along side the created Continuation, but this form is confusing # and does only rarely make sense. # # # Count from 0 to 10 # cc, counter = Continuation.create(0) # counter #~> 0..10 # cc.call(counter + 1) if counter < 10 # # # Implement something similar to Array#inject using Continuations. # # For simplicity's sake, this is not fully compatible with the real # # inject. Make sure that you understand Array#inject before you try # # to understand this. # class ::Array # def cc_inject(value = nil) # copy = self.clone # cc, result, item = Continuation.create(value, nil) # next_item = copy.shift # if result and item # # Aggregate the result using the block. # cc.call(yield(result, item), next_item) # elsif next_item # # item not yet set and Array is not empty: # # This means we did not get a value and thus need to use the # # first item from the Array before we can start using the # # block to aggregate the result. # cc.call(next_item, result) # end # # return result # end # end # [1,2,3,4,5].cc_inject { |acc, n| acc + n } # => 15 # def Continuation.create(*args, &block) args = [args] if not args.nil? and not args.is_a? Array # 1.6.8 compatibility cc = nil; result = callcc {|c| cc = c; block.call(cc) if block and args.empty?} result ||= args return *[cc, *result] end end facets-2.9.3/lib/standard/facets/rbconfig.rb0000644000004100000410000000257511714455226020773 0ustar www-datawww-data# An extended rendition of the Ruby's standard RbConfig module. module RbConfig # def self.inspect CONFIG.inspect end # Methodized lookup of config. def self.method_missing(s,*a,&b) s = s.to_s if CONFIG.key?(s) CONFIG[s] elsif CONFIG.key?(s.upcase) CONFIG[s.upcase] else super(s,*a,&b) end end # TODO: parse configure_args into methods too? # In case rubygems has already defined it. unless method_defined?(:datadir) # Return the path to the data directory associated with the # given library/package name. Normally this is just # # "#{Config::CONFIG['datadir']}/#{name}" # # but may be modified by tools like RubyGems to handle # versioned data directories. def self.datadir(package_name) File.join(CONFIG['datadir'], package_name) end end # def self.host_os CONFIG['host_os'] end def linux? host_os =~ /linux|cygwin/ end def mac? host_os =~ /mac|darwin/ end def bsd? host_os =~ /bsd/ end def windows? host_os =~ /mswin|mingw/ end def solaris? host_os =~ /solaris|sunos/ end # TODO: who knows what symbian returns? def symbian? host_os =~ /symbian/ end # def posix? linux? or mac? or bsd? or solaris? or begin fork do end true rescue NotImplementedError, NoMethodError false end end end