0.0
No commit activity in last 3 years
No release in over 3 years
This library provides a convenient ruby API for representation of an Arduino Library specification, including field and type validation, reading and writing the library.properties file, as well as downloading the official database of Arduino libraries, and offering a highly advanced searching functionality. This gem only offers Ruby API, but for command line usage please checkout the gem called "arli" — Arduino Library Dependency Manager that uses this library behind the scenes.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
0.0
No commit activity in last 3 years
No release in over 3 years
Custom form field_tag of range-slider with text_field type selector. You can either choose from drop down or enter your own value and the slider will auto-adjust or you can use the slider to adjust values. This all through on form field f.slide_selector. Check out https://github.com/Touqeer-tqr/custom-form for sample app
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
0.0
No commit activity in last 3 years
No release in over 3 years
# EventReporter EventReporter is a CSV parser and sorter. you can load a CSV and then search it. ## Installation $ gem install the_only_event_reporter_ever $ gem list event_reporter -d ## Usage After installation run: $ event_reporter Then Type 'load <filename>' to load records from a CSV $ Load event_attendees.csv Try these commands $ Find first_name sarah $Queue Print $Queue Save to <filename> ### Saving the queue accepts extensions JSON, XML, TXT, CSV. ## Contributing 1. Fork it 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new Pull Request
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
0.0
No release in over 3 years
Sinja is a Sinatra extension for quickly building RESTful, {json:api}-compliant web services, leveraging the excellent JSONAPI::Serializers gem for payload serialization. It enhances Sinatra's DSL to enable resource-, relationship-, and role-centric API development, and it configures Sinatra with the proper settings, MIME-types, filters, conditions, and error-handling. There are many parsing (deserializing), rendering (serializing), and other "JSON API" libraries available for Ruby, but relatively few that attempt to correctly implement the entire {json:api} server specification, including routing, request header and query parameter checking, and relationship side-loading. Sinja lets you focus on the business logic of your applications without worrying about the specification, and without pulling in a heavy framework like Rails. It's lightweight, ORM-agnostic, and Ember.js-friendly!
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Popularity
0.0
No release in over 3 years
Low commit activity in last 3 years
Return a variable if it's present (and optionally of the right type), otherwise a default or nil. Adds a top level demand() method, which replaces long lines of repetitive code to check for nil?/present?/empty?, etc., hard-to-read ternary operators (?:) and if statements. A block can also be specified, which only runs (with the variable) if the checks pass.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
0.0
No release in over 3 years
QuacksLike is a module for RSpec to add matchers that test if an object is fully duck-typed to pretend to be another class. This kind of thing is really only necessary when passing such an object as the return value in an API where you don't know exactly how it will be consumed, but it needs to "quack like an Array" or something. It does its job by checking every instance method in the class that the target object needs to "quack like" and makes sure the target both responds to that method name and that the arity of the method is appropriate.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Popularity
0.0
No release in over 3 years
QuacksLike is a module for RSpec to add matchers that test if an object is fully duck-typed to pretend to be another class. This kind of thing is really only necessary when passing such an object as the return value in an API where you don't know exactly how it will be consumed, but it needs to "quack like an Array" or something. It does its job by checking every instance method in the class that the target object needs to "quack like" and makes sure the target both responds to that method name and that the arity of the method is appropriate.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Popularity
0.0
No commit activity in last 3 years
No release in over 3 years
Create and manage configuration files in Ruby for Ruby. Jeckyl can be used to create a parameters hash from a simple config file written in Ruby, having run whatever checks you want on the file to ensure the values passed in are valid. All you need to do is define a class inheriting from Jeckyl, methods for each parameter, its default, whatever checking rules are appropriate and even a comment for generating templates etc. This is then used to parse a Ruby config file and create the parameters hash. Jeckyl comes complete with a utility to check a config file against a given class and to generate a default file for you to tailor. Type 'jeckyl readme' for more information.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
0.0
The project is in a healthy, maintained state
# foundationallib <h2>Finally, a cross-platform, portable, well-designed, secure, robust, maximally-efficient C foundational library &mdash; Making Engineering And Computing Fast, Secure, Responsive And Easy.</h2> <br> <ul class="features-list"> <li><strong>Enables better Engineering Solutions and Security broadly and foundationally where Software Creation or Development or Script Creation is concerned - whether this be on a local, business, governmental or international basis, and makes things easier - and Computing in General.</strong> Don't Reinvent the Wheel - Use Good Wheels - Be Safe And Secure.</li> <br> <li><strong>Enables a free-flowing dynamic computer usage that you need, deserve and should have, simply because you have a computer. With full speed and with robustness. You deserve to be able to use your computer wholly and fully, with proper and fast operations.</strong></li> <br><li><strong>Enables flexibility and power - makes C accessible to the masses (and faster and more secure) with easy usage and strives to bring people up, not degrade the character or actions of people.</strong> This is a fundamental and unequivocal philosophy difference between this library and many subsections of Software Engineering and the mainstream engineering establishment. For instance, in Python, you cannot read a file easily &ndash; you have to read it line-by-line or open a file, read the lines, then close it. With this library, you can efficiently read 10,000 files in one function call. This library gives power. Any common operation, there ought to be a powerful function for.<br><br>We should not bitch around with assembly when we don't want to; we should also have full speed. Some old "solutions" deliver neither, then culturally degrade programmers because their tools are bad - actually, it just degrades programmers, and gives them bad tools. COBOL is an example ...<br><br>Human technology is about empowerment &ndash; people must fight for it to be empowerment, we don't have time to have AI systems kill us because we want to have bad tools and be weak. We must fight.</li> </ul> <br> <ul> <h2>About Foundationallib</h2> <li>→<strong>Cross platform</strong> - works perfectly in embedded, server, desktop, and all platforms - tested for Windows and UNIX - 64-bit and 32-bit, includes a 3-aspect test suite, with more to come.</li> <li>→<strong>Bug free. Reliable. Dependable. Secure. Tested well.</strong></li> <li>→<strong>Zero Overhead</strong> - Only 1 byte due to the power of the error handling, can be configured will full power.</li> <li>→<strong>Static Inline Functions if you want them</strong> (optional) - Eliminating function call overhead to 0 if you wish, for improved performance.</li> <li>→<strong>Custom allocators</strong> - if you want it.</li> <li>→<strong>Custom error handling</strong> - if you want it.</li> <li>→<strong>Safe functions</strong> warn the programmer about NULL values and unused return values. Can be configured to not compile if not Secure. Optional null-check macros in every library function. Does not use any of <code>"gets", "fgets", "strcpy", "strcat", "sprintf", "vsprintf", "scanf", "fscanf", "system", "chown", "chmod", "chgrp", "alloca", "execl", "execle", "execlp", "execv", "execve", "execvp", "bcopy", "bzero"</code>. You can configure it to never use any unsafe functions.</li> <li>→<strong>Portable</strong> - works on all platforms, using platform specific features (using #ifdefs) to make functions better and faster.</li> <li>→<strong>Multithreading support</strong> (optional), with list_comprehension_multithreaded (accepts any number of threads, works in parallel using portable C11 threads)</li> <li>→<strong>Networking support</strong> (optional), using libcurl - making it extremely easy to download websites and arrays of websites - features other languages do not have.</li> <li>→Very good and thorough <strong>Error Handling</strong> and <strong>allocation overflow</strong> checking (good for <strong>Security and Robustness</strong>) in the functions. Allows the programmer to dynamically choose to catch all errors in the functions with a handler (default or custom), or to ignore them. No need to ALWAYS say "if (.....) if you don't want to. Can be changed at runtime.</li> <li>→<strong>Public Domain</strong> so you make the code how you want. (No need to "propitiate" to some "god" of some library).</li> <li>→<strong>Minimal abstractions or indirection of any kind or needless slow things that complicate things</strong> - macros, namespace collision, typedefs, structs, object-orientation messes, slow compilation times, bloat, etc., etc.</li> <li>→<strong>No namespace pollution</strong> - you can generate your <span style=font-style:normal;><b>own version</b></span> with any prefix you like!</li> <li>→<strong>Relies <span style=font-style:normal;>minimally</span> on C libraries - it can be fully decoupled from LIB C and can be statically linked.</strong></li> <li>→<span style=font-style:normal;><b>Very small</b></span> - 13K Lines of Code (including Doxygen comments and following of Best Practices)</li> <li>→<strong>No Linkage Issues or dependency hell</strong></li> <li>→<strong>Thorough and clear documentation</strong>, with examples of usage.</li> <li>→<strong>No licensing restrictions whatsoever - use it for your engineering project, your startup, your Fortune 500 company, your personal project, your throw-away script, your government.</strong></li> <li>→<strong>Makes C like Python or Perl or Ruby in many ways - or more easy</strong></li> <li>→<strong>Easy Straightforward Transpilation Support</strong> - to make current code, much faster - all without any bloat (See transpile_slow_scripting_into_c.rb). <li><h4>In many cases, there is now a direct mapping of functions from other languages into optimized C. See the example script in this repository. This makes optimizing your Python / Perl / Ruby / PHP etc. script very easy, either manually or through the use of AI.</h4></li> </ul> </p> </div> <div class=pane style='border: 0;border-right: 1px dotted rgb(200, 200, 200); background-color: rgb(255, 255, 190);'> <div class="library-details"><h2 style=color:green;>Foundationallib Features</h2> <p class=feature> <strong>Functional Programming Features</strong> - <code>map, reduce, filter,</code> List Comprehensions in C and much more!</p> <p class=feature><strong>Expands C's Primitives for easy manipulation of data types</strong> such as Arrays, Strings, <code>Dict</code>, <code>Set</code>, <code>FrozenDict</code>, <code>FrozenSet</code> - <strong>and enables easy manipulation, modification, alteration, comparison, sorting, counting, IO (printing) and duplication of these at a very comfortable level</strong> - something very, very rare in C or C++, <i>all without any overhead.</i></p> <p class=feature><strong>More comfortable IO</strong> - read and write entire files with ease, and convert complex types into strings or print them on the screen with ease. </p> <p class=feature><strong>A powerful general purpose Foundational Library</strong> - <i>which has anything and everything you need</i> - from <code>replace_all()</code> to <code>replace_memory()</code> to <code>find_last_of()</code> to to <code>list_comprehension()</code> to <code>shellescape()</code> to <code>read_file_into_string()</code> to <code>string_to_json()</code> to <code>string_to_uppercase()</code> to <code>to_title_case()</code> to <code>read_file_into_array()</code> to <code>read_files_into_array()</code> to <code>map()</code> to <code>reduce()</code> to <code>filter()</code> to <code>list_comprehension_multithreaded()</code> to <code>frozen_dict_new_instance()</code> to <code>backticks()</code> - everything you would want to make quick and optimally efficient C programs, this has it.</p> <div style='height: 1px; border: 0;border-bottom: 1px dashed rgb(200, 200, 200);'></div> <p class=performance><span>Helps to make programs hundreds of times faster than other languages with similar ease of creation.</span> <hr> <p class=feature><strong>Easily take advantage of CPU cores with list_comprehension_multithreaded()</strong>.<br><br>You can specify the number of threads, the transform and the filter functions, and this will transform your data - all in parallel. Don't have a multithreaded environment? Then disable it (set the flag).</p> <hr> <h3>You don't want to be reinventing the wheel and hoping that your memory allocation is secure enough - and then failing. <strong>Security Is Paramount.</strong></h3> <h3>You don't want to be waiting <span style='color:rgb(240, 0, 0);'>a day</span> for an operation to complete when it could take <span style='color:rgb(30, 30, 255);'>less than an hour</span>.</h3> <br><p>This library is founded on very strong and unequivocal goals and philosophy. In fact, I have written many articles about the foundation of this library and more relevantly the broader context. See the Articles folder - for some of the foundation of this library.</p> <br><p>This library is an ideal and a dream - not just a Software Library. As such, I would highly suggest that you support me in this mission. Even if it's different from the status quo. Are you a Rust or Zig fan? Then make a Rust or Zig version of this ideal. Let's go. Give me an email.</p> </div> </div> <br> No Copyright - Public Domain - 2023, Gregory Cohen <gregorycohennew@gmail.com> DONATION REQUEST: If this free software has helped you and you find it valuable, please consider making a donation to support the ongoing development and maintenance of this project. Your contribution helps ensure the availability of this library to the community and encourages further improvements. Donations can be made at: https://www.paypal.com/paypalme/cfoundationallib Note: The best way to contact me is through email, not social media. Please feel very free to email me if you want to express feedback, suggest an improvement, desire to collaborate on this free and open source project, want to support me, or want to create something great. Complacency and obstructionism and whining are not tolerated. I desire to make this library the best theoretically possible, so please, let us connect. <pre><code> Mirror Links Blog - https://foundationallib.wordpress.com/ Github - https://github.com/gregoryc/foundationallib Ruby Gem Mirror - https://rubygems.org/gems/foundational_lib Ruby Gem Mirror - https://rubygems.org/gems/foundational_lib2 Library Instagram - https://www.instagram.com/foundationallib Google Drive Mirrors ZIP - https://drive.google.com/file/d/1bK2njCRsH4waTm4LP16sloPQawk7JIR5/view?usp=sharing TAR.GZ - https://drive.google.com/file/d/1RCA1yy9R3cEqI_X9Lv0fxqh-zgNCK005/view?usp=sharing TAR.BZ2 - https://drive.google.com/file/d/1ljdlI_fEnMS_X5WmuhI1qavhgseWlD5j/view?usp=sharing </code></pre> <h1>This code is in the public domain, fully. You can do whatever you want with it. See docs.html for API reference. ![Alt text](https://github.com/gregoryc/foundationallib/raw/main/tools/pic.png) </h1> <h1>Here's some examples of some things you can do easily with Foundationallib.<br><br> <h3>Use it for scripting purposes...</h3> </h1> ![Alt text](https://github.com/gregoryc/foundationallib/raw/main/tools/pic2.png) <h1>Take control of the Web - in C.<br><br></h1> ![Alt text](https://github.com/gregoryc/foundationallib/raw/main/tools/pic3.png)
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
0.0
The project is in a healthy, maintained state
# foundationallib <h2>Finally, a cross-platform, portable, well-designed, secure, robust, maximally-efficient C foundational library &mdash; Making Engineering And Computing Fast, Secure, Responsive And Easy.</h2> <br> <h2><i>Library Uses - What It Does, What It Is, And What It Is A Solution For</i></h2> <ul class="features-list"> <li><strong>Enables better Engineering Solutions and Security broadly and foundationally where Software Creation or Development or Script Creation is concerned - whether this be on a local, business, governmental or international basis, and makes things easier - and Computing in General.</strong> Don't Reinvent the Wheel - Use Good Wheels - Be Safe And Secure.</li> <br> <li><strong>Enables a free-flowing dynamic computer usage that you need, deserve and should have, simply because you have a computer. With full speed and with robustness. You deserve to be able to use your computer wholly and fully, with proper and fast operations.</strong></li> <br><li><strong>Enables flexibility and power - makes C accessible to the masses (and faster and more secure) with easy usage and strives to bring people up, not degrade the character or actions of people.</strong> This is a fundamental and unequivocal philosophy difference between this library and many subsections of Software Engineering and the mainstream engineering establishment. For instance, in Python, you cannot read a file easily &ndash; you have to read it line-by-line or open a file, read the lines, then close it. With this library, you can efficiently read 10,000 files in one function call. This library gives power. Any common operation, there ought to be a powerful function for.<br><br>We should not bitch around with assembly when we don't want to; we should also have full speed. Some old "solutions" deliver neither, then culturally degrade programmers because their tools are bad - actually, it just degrades programmers, and gives them bad tools. COBOL is an example ...<br><br>Human technology is about empowerment &ndash; people must fight for it to be empowerment, we don't have time to have AI systems kill us because we want to have bad tools and be weak. We must fight.</li> </ul> <br> <ul> <h2><i>About Foundationallib</i></h2> <li>→<strong>Cross platform</strong> - works perfectly in embedded, server, desktop, and all platforms - tested for Windows and UNIX - 64-bit and 32-bit, includes a 3-aspect test suite, with more to come.</li> <li>→<strong>Bug free. Reliable. Dependable. Secure. Tested well.</strong></li> <li>→<strong>Zero Overhead</strong> - Only 1 byte due to the power of the error handling, can be configured will full power.</li> <li>→<strong>Static Inline Functions if you want them</strong> (optional) - Eliminating function call overhead to 0 if you wish, for improved performance.</li> <li>→<strong>Custom allocators</strong> - if you want it.</li> <li>→<strong>Custom error handling</strong> - if you want it.</li> <li>→<strong>Safe functions</strong> warn the programmer about NULL values and unused return values. Can be configured to not compile if not Secure. Optional null-check macros in every library function. Does not use any of <code>"gets", "fgets", "strcpy", "strcat", "sprintf", "vsprintf", "scanf", "fscanf", "system", "chown", "chmod", "chgrp", "alloca", "execl", "execle", "execlp", "execv", "execve", "execvp", "bcopy", "bzero"</code>. You can configure it to never use any unsafe functions.</li> <li>→<strong>Portable</strong> - works on all platforms, using platform specific features (using #ifdefs) to make functions better and faster.</li> <li>→<strong>Multithreading support</strong> (optional), with list_comprehension_multithreaded (accepts any number of threads, works in parallel using portable C11 threads)</li> <li>→<strong>Networking support</strong> (optional), using libcurl - making it extremely easy to download websites and arrays of websites - features other languages do not have.</li> <li>→Very good and thorough <strong>Error Handling</strong> and <strong>allocation overflow</strong> checking (good for <strong>Security and Robustness</strong>) in the functions. Allows the programmer to dynamically choose to catch all errors in the functions with a handler (default or custom), or to ignore them. No need to ALWAYS say "if (.....) if you don't want to. Can be changed at runtime.</li> <li>→<strong>Public Domain</strong> so you make the code how you want. (No need to "propitiate" to some "god" of some library).</li> <li>→<strong>Minimal abstractions or indirection of any kind or needless slow things that complicate things</strong> - macros, namespace collision, typedefs, structs, object-orientation messes, slow compilation times, bloat, etc., etc.</li> <li>→<strong>No namespace pollution</strong> - you can generate your <span style=font-style:normal;><b>own version</b></span> with any prefix you like!</li> <li>→<strong>Relies <span style=font-style:normal;>minimally</span> on C libraries - it can be fully decoupled from LIB C and can be statically linked.</strong></li> <li>→<span style=font-style:normal;><b>Very small</b></span> - 13K Lines of Code (including Doxygen comments and following of Best Practices)</li> <li>→<strong>No Linkage Issues or dependency hell</strong></li> <li>→<strong>Thorough and clear documentation</strong>, with examples of usage.</li> <li>→<strong>No licensing restrictions whatsoever - use it for your engineering project, your startup, your Fortune 500 company, your personal project, your throw-away script, your government.</strong></li> <li>→<strong>Makes C like Python or Perl or Ruby in many ways - or more easy</strong></li> <li>→<strong>Easy Straightforward Transpilation Support</strong> - to make current code, much faster - all without any bloat (See transpile_slow_scripting_into_c.rb). <li><h4>In many cases, there is now a direct mapping of functions from other languages into optimized C. See the example script in this repository. This makes optimizing your Python / Perl / Ruby / PHP etc. script very easy, either manually or through the use of AI.</h4></li> </ul> </p> </div> <div class=pane style='border: 0;border-right: 1px dotted rgb(200, 200, 200); background-color: rgb(255, 255, 190);'> <div class="library-details"><h2 style=color:green;><i>Foundationallib Features</i></h2> <p class=feature> <strong>Functional Programming Features</strong> - <code>map, reduce, filter,</code> List Comprehensions in C and much more!</p> <p class=feature><strong>Expands C's Primitives for easy manipulation of data types</strong> such as Arrays, Strings, <code>Dict</code>, <code>Set</code>, <code>FrozenDict</code>, <code>FrozenSet</code> - <strong>and enables easy manipulation, modification, alteration, comparison, sorting, counting, IO (printing) and duplication of these at a very comfortable level</strong> - something very, very rare in C or C++, <i>all without any overhead.</i></p> <p class=feature><strong>More comfortable IO</strong> - read and write entire files with ease, and convert complex types into strings or print them on the screen with ease. </p> <p class=feature><strong>A powerful general purpose Foundational Library</strong> - <i>which has anything and everything you need</i> - from <code>replace_all()</code> to <code>replace_memory()</code> to <code>find_last_of()</code> to to <code>list_comprehension()</code> to <code>shellescape()</code> to <code>read_file_into_string()</code> to <code>string_to_json()</code> to <code>string_to_uppercase()</code> to <code>to_title_case()</code> to <code>read_file_into_array()</code> to <code>read_files_into_array()</code> to <code>map()</code> to <code>reduce()</code> to <code>filter()</code> to <code>list_comprehension_multithreaded()</code> to <code>frozen_dict_new_instance()</code> to <code>backticks()</code> - everything you would want to make quick and optimally efficient C programs, this has it.</p> <div style='height: 1px; border: 0;border-bottom: 1px dashed rgb(200, 200, 200);'></div> <p class=performance><span>Helps to make programs hundreds of times faster than other languages with similar ease of creation.</span> <hr> <p class=feature><strong>Easily take advantage of CPU cores with list_comprehension_multithreaded()</strong>.<br><br>You can specify the number of threads, the transform and the filter functions, and this will transform your data - all in parallel. Don't have a multithreaded environment? Then disable it (set the flag).</p> <hr> <h3>You don't want to be reinventing the wheel and hoping that your memory allocation is secure enough - and then failing. <strong>Security Is Paramount.</strong></h3> <h3>You don't want to be waiting <span style='color:rgb(240, 0, 0);'>a day</span> for an operation to complete when it could take <span style='color:rgb(30, 30, 255);'>less than an hour</span>.</h3> <br><p>This library is founded on very strong and unequivocal goals and philosophy. In fact, I have written many articles about the foundation of this library and more relevantly the broader context. See the Articles folder - for some of the foundation of this library.</p> <br><p>This library is an ideal and a dream - not just a Software Library. As such, I would highly suggest that you support me in this mission. Even if it's different from the status quo. Are you a Rust or Zig fan? Then make a Rust or Zig version of this ideal. Let's go. Give me an email.</p> </div> </div> <br> No Copyright - Public Domain - 2023, Gregory Cohen <gregorycohennew@gmail.com> DONATION REQUEST: If this free software has helped you and you find it valuable, please consider making a donation to support the ongoing development and maintenance of this project. Your contribution helps ensure the availability of this library to the community and encourages further improvements. Donations can be made at: https://www.paypal.com/paypalme/cfoundationallib Note: The best way to contact me is through email, not social media. Please feel very free to email me if you want to express feedback, suggest an improvement, desire to collaborate on this free and open source project, want to support me, or want to create something great. Complacency and obstructionism and whining are not tolerated. I desire to make this library the best theoretically possible, so please, let us connect. <h1>This code is in the public domain, fully. You can do whatever you want with it. See docs.html for API reference. ![Alt text](https://github.com/gregoryc/foundationallib/raw/main/tools/pic.png) </h1> <h1>Here's some examples of some things you can do easily with Foundationallib.<br><br> <h3>Use it for scripting purposes...</h3> </h1> ![Alt text](https://github.com/gregoryc/foundationallib/raw/main/tools/pic2.png) <h1>Take control of the Web - in C.<br><br></h1> ![Alt text](https://github.com/gregoryc/foundationallib/raw/main/tools/pic3.png)
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
0.0
No release in over 3 years
Ame Ame provides a simple command-line interface API for Ruby¹. It can be used to provide both simple interfaces like that of ‹rm›² and complex ones like that of ‹git›³. It uses Ruby’s own classes, methods, and argument lists to provide an interface that is both simple to use from the command-line side and from the Ruby side. The provided command-line interface is flexible and follows commond standards for command-line processing. ¹ See http://ruby-lang.org/ ² See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/rm.html ³ See http://git-scm.com/docs/ § Usage Let’s begin by looking at two examples, one where we mimic the POSIX¹ command-line interface to the ‹rm› command. Looking at the entry² in the standard, ‹rm› takes the following options: = -f. = Do not prompt for confirmation. = -i. = Prompt for confirmation. = -R. = Remove file hierarchies. = -r. = Equivalent to /-r/. It also takes the following arguments: = FILE. = A pathname or directory entry to be removed. And actually allows one or more of these /FILE/ arguments to be given. We also note that the ‹rm› command is described as a command to “remove directory entries”. ¹ See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/contents.html ² See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/rm.html Let’s turn this specification into one using Ame’s API. We begin by adding a flag for each of the options listed above: class Rm &lt; Ame::Root flag 'f', '', false, 'Do not prompt for confirmation' flag 'i', '', nil, 'Prompt for confirmation' do |options| options['f'] = false end flag 'R', '', false, 'Remove file hierarchies' flag 'r', '', nil, 'Equivalent to -R' do |options| options['r'] = true end A flag¹ is a boolean option that doesn’t take an argument. Each flag gets a short and long name, where an empty name means that there’s no corresponding short or long name for the flag, a default value (true, false, or nil), and a description of what the flag does. Each flag can also optionally take a block that can do further processing. In this case we use this block to modify the Hash that maps option names to their values passed to the block to set other flags’ values than the ones that the block is associated with. As these flags (‘i’ and ‘r’) aren’t themselves of interest, their default values have been set to nil, which means that they won’t be included in the Hash that maps option names to their values when passed to the method. ¹ See http://disu.se/software/ame-1.0/api/user/Ame/Class#flag-class-method There are quite a few other kinds of options besides flags that can be defined using Ame, but flags are all that are required for this example. We’ll get to the other kinds in later examples. Next we add a “splus” argument. splus 'FILE', String, 'File to remove' A splus¹ argument is like a Ruby “splat”, that is, an Array argument at the end of the argument list to a method preceded by a star, except that a splus requires at least one argument. A splus argument gets a name for the argument (‹FILE›), the type of argument it represents (String), and a description. ¹ See http://disu.se/software/ame-1.0/api/user/Ame/Class#splus-class-method Then we add a description of the command (method) itself: description 'Remove directory entries' Descriptions¹ will be used in help output to assist the user in using the command. ¹ See http://disu.se/software/ame-1.0/api/user/Ame/Class#description-class-method Finally, we add the Ruby method that’ll implement the command (all preceding code included here for completeness): class Rm &lt; Ame::Root version '1.0.0' flag 'f', '', false, 'Do not prompt for confirmation' flag 'i', '', nil, 'Prompt for confirmation' do |options| options['f'] = false end flag 'R', '', false, 'Remove file hierarchies' flag 'r', '', nil, 'Equivalent to -R' do |options| options['r'] = true end splus 'FILE', String, 'File to remove' description 'Remove directory entries' def rm(files, options = {}) require 'fileutils' FileUtils.send options['R'] ? :rm_r : :rm, [first] + rest, :force =&gt; options['f'] end end Actually, another bit of code was also added, namely version '1.0.0' This sets the version¹ String of the command. This information is used when the command is invoked with the “‹--version›” flag. This flag is automatically added, so you don’t need to add it yourself. Another flag, “‹--help›”, is also added automatically. When given, this flag’ll make Ame output usage information of the command. ¹ See http://disu.se/software/ame-1.0/api/user/Ame/Class#version-class-method To actually run the command, all you need to do is invoke Rm.process This’ll invoke the command using the command-line arguments stored in ‹ARGV›, but you can also specify other ones if you want to: Rm.process 'rm', %w[-r /tmp/*] The first argument to #process¹ is the name of the method to invoke, which defaults to ‹File.basename($0)›, and the second argument is an Array of Strings that should be processed as command-line arguments passed to the command. ¹ See http://disu.se/software/ame-1.0/api/user/Ame/Class#process-class-method If you’d store the complete ‹Rm› class defined above in a file called ‹rm› and add ‹#! /usr/bin/ruby -w› at the beginning and ‹Rm.process› at the end, you’d have a fully functional ‹rm› command (after making it executable). Let’s see it in action: % rm --help Usage: rm [OPTIONS]... FILE... Remove directory entries Arguments: FILE... File to remove Options: -R Remove file hierarchies -f Do not prompt for confirmation --help Display help for this method -i Prompt for confirmation -r Equivalent to -R --version Display version information % rm --version rm 1.0.0 Some commands are more complex than ‹rm›. For example, ‹git›¹ has a rather complex command-line interface. We won’t mimic it all here, but let’s introduce the rest of the Ame API using a fake ‹git› clone as an example. ¹ See http://git-scm.com/docs/ ‹Git› uses sub-commands to achieve most things. Implementing sub-commands with Ame is done using a “dispatch”. We’ll discuss dispatches in more detail later, but suffice it to say that a dispatch delegates processing to a child class that’ll handle the sub-command in question. We begin by defining our main ‹git› command using a class called ‹Git› under the ‹Git::CLI› namespace: module Git end class Git::CLI &lt; Ame::Root version '1.0.0' class Git &lt; Ame::Class description 'The stupid content tracker' def initialize; end We’re setting things up to use the ‹Git› class as a dispatch in the ‹Git::CLI› class. The description on the ‹initialize› method will be used as a description of the ‹git› dispatch command itself. Next, let’s add the ‹format-patch›¹ sub-command: description 'Prepare patches for e-mail submission' flag ?n, 'numbered', false, 'Name output in [PATCH n/m] format' flag ?N, 'no-numbered', nil, 'Name output in [PATCH] format' do |options| options['numbered'] = false end toggle ?s, 'signoff', false, 'Add Signed-off-by: line to the commit message' switch '', 'thread', 'STYLE', nil, Ame::Types::Enumeration[:shallow, :deep], 'Controls addition of In-Reply-To and References headers' flag '', 'no-thread', nil, 'Disables addition of In-Reply-To and Reference headers' do |options, _| options.delete 'thread' end option '', 'start-number', 'N', 1, 'Start numbering the patches at N instead of 1' multioption '', 'to', 'ADDRESS', String, 'Add a To: header to the email headers' optional 'SINCE', 'N/A', 'Generate patches for commits after SINCE' def format_patch(since = '', options = {}) p since, options end ¹ See http://git-scm.com/docs/git-format-patch/ We’re using quite a few new Ame commands here. Let’s look at each in turn: toggle ?s, 'signoff', false, 'Add Signed-off-by: line to the commit message' A “toggle”¹ is a flag that also has an inverse. Beyond the flags ‘s’ and “signoff”, the toggle also defines “no-signoff”, which will set “signoff” to false. This is useful if you want to support configuration files that set “signoff”’s default to true, but still allow it to be overridden on the command line. ¹ See http://disu.se/software/ame-1.0/api/user/Ame/Class#toggle-class-method When using the short form of a toggle (and flag and switch), multiple ones may be juxtaposed after the initial one. For example, “‹-sn›” is equivalent to “‹-s -n›” to “git format-patch›”. switch '', 'thread', 'STYLE', nil, Ame::Types::Enumeration[:shallow, :deep], 'Controls addition of In-Reply-To and References headers' A “switch”¹ is an option that takes an optional argument. This allows you to have separate defaults for when the switch isn’t present on the command line and for when it’s given without an argument. The third argument to a switch is the name of the argument. We’re also introducing a new concept here in ‹Ame::Types::Enumeration›. An enumeration² allows you to limit the allowed input to a set of Symbols. An enumeration also has a default value in the first item to its constructor (which is aliased as ‹.[]›). In this case, the “thread” switch defaults to nil, but, when given, will default to ‹:shallow› if no argument is given. If an argument is given it must be either “shallow” or “deep”. A switch isn’t required to take an enumeration as its argument default and can take any kind of default value for its argument that Ame knows how to handle. We’ll look at this in more detail later, but know that the type of the default value will be used to inform Ame how to parse a command-line argument into a Ruby value. An argument to a switch must be given, in this case, as “‹--thread=deep›” on the command line. ¹ See http://disu.se/software/ame-1.0/api/user/Ame/Class#switch-class-method ² See http://disu.se/software/ame-1.0/api/user/Ame/Types/Enumeration/ option '', 'start-number', 'N', 1, 'Start numbering the patches at N instead of 1' An “option”¹ is an option that takes an argument. The argument must always be present and may be given, in this case, as “‹--start-number=2›” or “‹--start-number 2›” on the command line. For a short-form option, anything that follows the option is seen as an argument, so assuming that “start-number” also had a short name of ‘S’, “‹-S2›” would be equivalent to “‹-S 2›”, which would be equivalent to “‹--start-number 2›”. Note that “‹-snS2›” would still work as expected. ¹ See http://disu.se/software/ame-1.0/api/user/Ame/Class#option-class-method multioption '', 'to', 'ADDRESS', String, 'Add a To: header to the email headers' A “multioption”¹ is an option that takes an argument and may be repeated any number of times. Each argument will be added to an Array stored in the Hash that maps option names to their values. Instead of taking a default argument, it takes a type for the argument (String, in this case). Again, types are used to inform Ame how to parse command-line arguments into Ruby values. ¹ See http://disu.se/software/ame-1.0/api/user/Ame/Class#multioption-class-method optional 'SINCE', 'N/A', 'Generate patches for commits after SINCE' An “optional”¹ argument is an argument that isn’t required. If it’s not present on the command line it’ll get its default value (the String ‹'N/A'›, in this case). ¹ See http://disu.se/software/ame-1.0/api/user/Ame/Class#optional-class-method We’ve now covered all kinds of options and one new kind of argument. There are three more types of argument (one that we’ve already seen and two new) that we’ll look into now: “argument”, “splat”, and “splus”. description 'Annotate file lines with commit information' argument 'FILE', String, 'File to annotate' def annotate(file) p file end An “argument”¹ is an argument that’s required. If it’s not present on the command line, an error will be raised (and by default reported to the terminal). As it’s required, it doesn’t take a default, but rather a type. ¹ See http://disu.se/software/ame-1.0/api/user/Ame/Class#argument-class-method description 'Add file contents to the index' splat 'PATHSPEC', String, 'Files to add content from' def add(paths) p paths end A “splat”¹ is an argument that’s not required, but may be given any number of times. The type of a splat is the type of one argument and the type of a splat as a whole is an Array of values of that type. ¹ See http://disu.se/software/ame-1.0/api/user/Ame/Class#splat-class-method description 'Display gitattributes information' splus 'PATHNAME', String, 'Files to list attributes of' def check_attr(paths) p paths end A “splus”¹ is an argument that’s required, but may also be given any number of times. The type of a splus is the type of one argument and the type of a splus as a whole is an Array of values of that type. ¹ See http://disu.se/software/ame-1.0/api/user/Ame/Class#splus-class-method Now that we’ve seen all kinds of options and arguments, let’s look on an additional tool at our disposal, the dispatch¹. class Remote &lt; Ame::Class description 'Manage set of remote repositories' def initialize; end description 'Shows a list of existing remotes' flag 'v', 'verbose', false, 'Show remote URL after name' def list(options = {}) p options end description 'Adds a remote named NAME for the repository at URL' argument 'name', String, 'Name of the remote to add' argument 'url', String, 'URL to the repository of the remote to add' def add(name, url) p name, url end end ¹ See http://disu.se/software/ame-1.0/api/user/Ame/Class#dispatch-class-method Here we’re defining a child class to Git::CLI::Git called “Remote” that doesn’t introduce anything new. Then we set up the dispatch: dispatch Remote, :default =&gt; 'list' This adds a method called “remote” to Git::CLI::Git that will dispatch processing of the command line to an instance of the Remote class when “‹git remote›” is seen on the command line. The “remote” method expects an argument that’ll be used to decide what sub-command to execute. Here we’ve specified that in the absence of such an argument, the “list” method should be invoked. We add the same kind of dispatch to Git under Git::CLI: dispatch Git and then we’re done. Here’s all the previous code in its entirety: module Git end class Git::CLI &lt; Ame::Root version '1.0.0' class Git &lt; Ame::Class description 'The stupid content tracker' def initialize; end description 'Prepare patches for e-mail submission' flag ?n, 'numbered', false, 'Name output in [PATCH n/m] format' flag ?N, 'no-numbered', nil, 'Name output in [PATCH] format' do |options| options['numbered'] = false end toggle ?s, 'signoff', false, 'Add Signed-off-by: line to the commit message' switch '', 'thread', 'STYLE', nil, Ame::Types::Enumeration[:shallow, :deep], 'Controls addition of In-Reply-To and References headers' flag '', 'no-thread', nil, 'Disables addition of In-Reply-To and Reference headers' do |options, _| options.delete 'thread' end option '', 'start-number', 'N', 1, 'Start numbering the patches at N instead of 1' multioption '', 'to', 'ADDRESS', String, 'Add a To: header to the email headers' optional 'SINCE', 'N/A', 'Generate patches for commits after SINCE' def format_patch(since = '', options = {}) p since, options end description 'Annotate file lines with commit information' argument 'FILE', String, 'File to annotate' def annotate(file) p file end description 'Add file contents to the index' splat 'PATHSPEC', String, 'Files to add content from' def add(paths) p paths end description 'Display gitattributes information' splus 'PATHNAME', String, 'Files to list attributes of' def check_attr(paths) p paths end class Remote &lt; Ame::Class description 'Manage set of remote repositories' def initialize; end description 'Shows a list of existing remotes' flag 'v', 'verbose', false, 'Show remote URL after name' def list(options = {}) p options end description 'Adds a remote named NAME for the repository at URL' argument 'name', String, 'Name of the remote to add' argument 'url', String, 'URL to the repository of the remote to add' def add(name, url) p name, url end end dispatch Remote, :default =&gt; 'list' end dispatch Git end If we put this code in a file called “git” and add ‹#! /usr/bin/ruby -w› at the beginning and ‹Git::CLI.process› at the end, you’ll have a very incomplete git command-line interface on your hands. Let’s look at what some of its ‹--help› output looks like: % git --help Usage: git [OPTIONS]... METHOD [ARGUMENTS]... The stupid content tracker Arguments: METHOD Method to run [ARGUMENTS]... Arguments to pass to METHOD Options: --help Display help for this method --version Display version information Methods: add Add file contents to the index annotate Annotate file lines with commit information check-attr Display gitattributes information format-patch Prepare patches for e-mail submission remote Manage set of remote repositories % git format-patch --help Usage: git format-patch [OPTIONS]... [SINCE] Prepare patches for e-mail submission Arguments: [SINCE=N/A] Generate patches for commits after SINCE Options: -N, --no-numbered Name output in [PATCH] format --help Display help for this method -n, --numbered Name output in [PATCH n/m] format --no-thread Disables addition of In-Reply-To and Reference headers -s, --signoff Add Signed-off-by: line to the commit message --start-number=N Start numbering the patches at N instead of 1 --thread[=STYLE] Controls addition of In-Reply-To and References headers --to=ADDRESS* Add a To: header to the email headers % git remote --help Usage: git remote [OPTIONS]... [METHOD] [ARGUMENTS]... Manage set of remote repositories Arguments: [METHOD=list] Method to run [ARGUMENTS]... Arguments to pass to METHOD Options: --help Display help for this method Methods: add Adds a remote named NAME for the repository at URL list Shows a list of existing remotes § API The previous section gave an introduction to the whole user API in an informal and introductory way. For an indepth reference to the user API, see the {user API documentation}¹. ¹ See http://disu.se/software/ame-1.0/api/user/Ame/ If you want to extend the API or use it in some way other than as a command-line-interface writer, see the {developer API documentation}¹. ¹ See http://disu.se/software/ame-1.0/api/developer/Ame/ § Financing Currently, most of my time is spent at my day job and in my rather busy private life. Please motivate me to spend time on this piece of software by donating some of your money to this project. Yeah, I realize that requesting money to develop software is a bit, well, capitalistic of me. But please realize that I live in a capitalistic society and I need money to have other people give me the things that I need to continue living under the rules of said society. So, if you feel that this piece of software has helped you out enough to warrant a reward, please PayPal a donation to now@disu.se¹. Thanks! Your support won’t go unnoticed! ¹ Send a donation: https://www.paypal.com/cgi-bin/webscr?cmd=_donations&amp;business=now@disu.se&amp;item_name=Ame § Reporting Bugs Please report any bugs that you encounter to the {issue tracker}¹. ¹ See https://github.com/now/ame/issues § Authors Nikolai Weibull wrote the code, the tests, the documentation, and this README. § Licensing Ame is free software: you may redistribute it and/or modify it under the terms of the {GNU Lesser General Public License, version 3}¹ or later², as published by the {Free Software Foundation}³. ¹ See http://disu.se/licenses/lgpl-3.0/ ² See http://gnu.org/licenses/ ³ See http://fsf.org/
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Popularity
0.0
No release in over 3 years
Lookout Lookout is a unit testing framework for Ruby¹ that puts your results in focus. Tests (expectations) are written as follows expect 2 do 1 + 1 end expect ArgumentError do Integer('1 + 1') end expect Array do [1, 2, 3].select{ |i| i % 2 == 0 } end expect [2, 4, 6] do [1, 2, 3].map{ |i| i * 2 } end Lookout is designed to encourage – force, even – unit testing best practices such as • Setting up only one expectation per test • Not setting expectations on non-public APIs • Test isolation This is done by • Only allowing one expectation to be set per test • Providing no (additional) way of accessing private state • Providing no setup and tear-down methods, nor a method of providing test helpers Other important points are • Putting the expected outcome of a test in focus with the steps of the calculation of the actual result only as a secondary concern • A focus on code readability by providing no mechanism for describing an expectation other than the code in the expectation itself • A unified syntax for setting up both state-based and behavior-based expectations The way Lookout works has been heavily influenced by expectations², by {Jay Fields}³. The code base was once also heavily based on expectations, based at Subversion {revision 76}⁴. A lot has happened since then and all of the work past that revision are due to {Nikolai Weibull}⁵. ¹ Ruby: http://ruby-lang.org/ ² Expectations: http://expectations.rubyforge.org/ ³ Jay Fields’s blog: http://blog.jayfields.com/ ⁴ Lookout revision 76: https://github.com/now/lookout/commit/537bedf3e5b3eb4b31c066b3266f42964ac35ebe ⁵ Nikolai Weibull’s home page: http://disu.se/ § Installation Install Lookout with % gem install lookout § Usage Lookout allows you to set expectations on an object’s state or behavior. We’ll begin by looking at state expectations and then take a look at expectations on behavior. § Expectations on State: Literals An expectation can be made on the result of a computation: expect 2 do 1 + 1 end Most objects, in fact, have their state expectations checked by invoking ‹#==› on the expected value with the result as its argument. Checking that a result is within a given range is also simple: expect 0.099..0.101 do 0.4 - 0.3 end Here, the more general ‹#===› is being used on the ‹Range›. § Regexps ‹Strings› of course match against ‹Strings›: expect 'ab' do 'abc'[0..1] end but we can also match a ‹String› against a ‹Regexp›: expect %r{a substring} do 'a string with a substring' end (Note the use of ‹%r{…}› to avoid warnings that will be generated when Ruby parses ‹expect /…/›.) § Modules Checking that the result includes a certain module is done by expecting the ‹Module›. expect Enumerable do [] end This, due to the nature of Ruby, of course also works for classes (as they are also modules): expect String do 'a string' end This doesn’t hinder us from expecting the actual ‹Module› itself: expect Enumerable do Enumerable end or the ‹Class›: expect String do String end for obvious reasons. As you may have figured out yourself, this is accomplished by first trying ‹#==› and, if it returns ‹false›, then trying ‹#===› on the expected ‹Module›. This is also true of ‹Ranges› and ‹Regexps›. § Booleans Truthfulness is expected with ‹true› and ‹false›: expect true do 1 end expect false do nil end Results equaling ‹true› or ‹false› are slightly different: expect TrueClass do true end expect FalseClass do false end The rationale for this is that you should only care if the result of a computation evaluates to a value that Ruby considers to be either true or false, not the exact literals ‹true› or ‹false›. § IO Expecting output on an IO object is also common: expect output("abc\ndef\n") do |io| io.puts 'abc', 'def' end This can be used to capture the output of a formatter that takes an output object as a parameter. § Warnings Expecting warnings from code isn’t very common, but should be done: expect warning('this is your final one!') do warn 'this is your final one!' end expect warning('this is your final one!') do warn '%s:%d: warning: this is your final one!' % [__FILE__, __LINE__] end ‹$VERBOSE› is set to ‹true› during the execution of the block, so you don’t need to do so yourself. If you have other code that depends on the value of $VERBOSE, that can be done with ‹#with_verbose› expect nil do with_verbose nil do $VERBOSE end end § Errors You should always be expecting errors from – and in, but that’s a different story – your code: expect ArgumentError do Integer('1 + 1') end Often, not only the type of the error, but its description, is important to check: expect StandardError.new('message') do raise StandardError.new('message') end As with ‹Strings›, ‹Regexps› can be used to check the error description: expect StandardError.new(/mess/) do raise StandardError.new('message') end § Queries Through Symbols Symbols are generally matched against symbols, but as a special case, symbols ending with ‹?› are seen as expectations on the result of query methods on the result of the block, given that the method is of zero arity and that the result isn’t a Symbol itself. Simply expect a symbol ending with ‹?›: expect :empty? do [] end To expect it’s negation, expect the same symbol beginning with ‹not_›: expect :not_nil? do [1, 2, 3] end This is the same as expect true do [].empty? end and expect false do [1, 2, 3].empty? end but provides much clearer failure messages. It also makes the expectation’s intent a lot clearer. § Queries By Proxy There’s also a way to make the expectations of query methods explicit by invoking methods on the result of the block. For example, to check that the even elements of the Array ‹[1, 2, 3]› include ‹1› you could write expect result.to.include? 1 do [1, 2, 3].reject{ |e| e.even? } end You could likewise check that the result doesn’t include 2: expect result.not.to.include? 2 do [1, 2, 3].reject{ |e| e.even? } end This is the same as (and executes a little bit slower than) writing expect false do [1, 2, 3].reject{ |e| e.even? }.include? 2 end but provides much clearer failure messages. Given that these two last examples would fail, you’d get a message saying “[1, 2, 3]#include?(2)” instead of the terser “true≠false”. It also clearly separates the actual expectation from the set-up. The keyword for this kind of expectations is ‹result›. This may be followed by any of the methods • ‹#not› • ‹#to› • ‹#be› • ‹#have› or any other method you will want to call on the result. The methods ‹#to›, ‹#be›, and ‹#have› do nothing except improve readability. The ‹#not› method inverts the expectation. § Literal Literals If you need to literally check against any of the types of objects otherwise treated specially, that is, any instances of • ‹Module› • ‹Range› • ‹Regexp› • ‹Exception› • ‹Symbol›, given that it ends with ‹?› you can do so by wrapping it in ‹literal(…)›: expect literal(:empty?) do :empty? end You almost never need to do this, as, for all but symbols, instances will match accordingly as well. § Expectations on Behavior We expect our objects to be on their best behavior. Lookout allows you to make sure that they are. Reception expectations let us verify that a method is called in the way that we expect it to be: expect mock.to.receive.to_str(without_arguments){ '123' } do |o| o.to_str end Here, ‹#mock› creates a mock object, an object that doesn’t respond to anything unless you tell it to. We tell it to expect to receive a call to ‹#to_str› without arguments and have ‹#to_str› return ‹'123'› when called. The mock object is then passed in to the block so that the expectations placed upon it can be fulfilled. Sometimes we only want to make sure that a method is called in the way that we expect it to be, but we don’t care if any other methods are called on the object. A stub object, created with ‹#stub›, expects any method and returns a stub object that, again, expects any method, and thus fits the bill. expect stub.to.receive.to_str(without_arguments){ '123' } do |o| o.to_str if o.convertable? end You don’t have to use a mock object to verify that a method is called: expect Object.to.receive.name do Object.name end As you have figured out by now, the expected method call is set up by calling ‹#receive› after ‹#to›. ‹#Receive› is followed by a call to the method to expect with any expected arguments. The body of the expected method can be given as the block to the method. Finally, an expected invocation count may follow the method. Let’s look at this formal specification in more detail. The expected method arguments may be given in a variety of ways. Let’s introduce them by giving some examples: expect mock.to.receive.a do |m| m.a end Here, the method ‹#a› must be called with any number of arguments. It may be called any number of times, but it must be called at least once. If a method must receive exactly one argument, you can use ‹Object›, as the same matching rules apply for arguments as they do for state expectations: expect mock.to.receive.a(Object) do |m| m.a 0 end If a method must receive a specific argument, you can use that argument: expect mock.to.receive.a(1..2) do |m| m.a 1 end Again, the same matching rules apply for arguments as they do for state expectations, so the previous example expects a call to ‹#a› with 1, 2, or the Range 1..2 as an argument on ‹m›. If a method must be invoked without any arguments you can use ‹without_arguments›: expect mock.to.receive.a(without_arguments) do |m| m.a end You can of course use both ‹Object› and actual arguments: expect mock.to.receive.a(Object, 2, Object) do |m| m.a nil, 2, '3' end The body of the expected method may be given as the block. Here, calling ‹#a› on ‹m› will give the result ‹1›: expect mock.to.receive.a{ 1 } do |m| raise 'not 1' unless m.a == 1 end If no body has been given, the result will be a stub object. To take a block, grab a block parameter and ‹#call› it: expect mock.to.receive.a{ |&b| b.call(1) } do |m| j = 0 m.a{ |i| j = i } raise 'not 1' unless j == 1 end To simulate an ‹#each›-like method, ‹#call› the block several times. Invocation count expectations can be set if the default expectation of “at least once” isn’t good enough. The following expectations are possible • ‹#at_most_once› • ‹#once› • ‹#at_least_once› • ‹#twice› And, for a given ‹N›, • ‹#at_most(N)› • ‹#exactly(N)› • ‹#at_least(N)› § Utilities: Stubs Method stubs are another useful thing to have in a unit testing framework. Sometimes you need to override a method that does something a test shouldn’t do, like access and alter bank accounts. We can override – stub out – a method by using the ‹#stub› method. Let’s assume that we have an ‹Account› class that has two methods, ‹#slips› and ‹#total›. ‹#Slips› retrieves the bank slips that keep track of your deposits to the ‹Account› from a database. ‹#Total› sums the ‹#slips›. In the following test we want to make sure that ‹#total› does what it should do without accessing the database. We therefore stub out ‹#slips› and make it return something that we can easily control. expect 6 do |m| stub(Class.new{ def slips raise 'database not available' end def total slips.reduce(0){ |m, n| m.to_i + n.to_i } end }.new, :slips => [1, 2, 3]){ |account| account.total } end To make it easy to create objects with a set of stubbed methods there’s also a convenience method: expect 3 do s = stub(:a => 1, :b => 2) s.a + s.b end This short-hand notation can also be used for the expected value: expect stub(:a => 1, :b => 2).to.receive.a do |o| o.a + o.b end and also works for mock objects: expect mock(:a => 2, :b => 2).to.receive.a do |o| o.a + o.b end Blocks are also allowed when defining stub methods: expect 3 do s = stub(:a => proc{ |a, b| a + b }) s.a(1, 2) end If need be, we can stub out a specific method on an object: expect 'def' do stub('abc', :to_str => 'def'){ |a| a.to_str } end The stub is active during the execution of the block. § Overriding Constants Sometimes you need to override the value of a constant during the execution of some code. Use ‹#with_const› to do just that: expect 'hello' do with_const 'A::B::C', 'hello' do A::B::C end end Here, the constant ‹A::B::C› is set to ‹'hello'› during the execution of the block. None of the constants ‹A›, ‹B›, and ‹C› need to exist for this to work. If a constant doesn’t exist it’s created and set to a new, empty, ‹Module›. The value of ‹A::B::C›, if any, is restored after the block returns and any constants that didn’t previously exist are removed. § Overriding Environment Variables Another thing you often need to control in your tests is the value of environment variables. Depending on such global values is, of course, not a good practice, but is often unavoidable when working with external libraries. ‹#With_env› allows you to override the value of environment variables during the execution of a block by giving it a ‹Hash› of key/value pairs where the key is the name of the environment variable and the value is the value that it should have during the execution of that block: expect 'hello' do with_env 'INTRO' => 'hello' do ENV['INTRO'] end end Any overridden values are restored and any keys that weren’t previously a part of the environment are removed when the block returns. § Overriding Globals You may also want to override the value of a global temporarily: expect 'hello' do with_global :$stdout, StringIO.new do print 'hello' $stdout.string end end You thus provide the name of the global and a value that it should take during the execution of a block of code. The block gets passed the overridden value, should you need it: expect true do with_global :$stdout, StringIO.new do |overridden| $stdout != overridden end end § Integration Lookout can be used from Rake¹. Simply install Lookout-Rake²: % gem install lookout-rake and add the following code to your Rakefile require 'lookout-rake-3.0' Lookout::Rake::Tasks::Test.new Make sure to read up on using Lookout-Rake for further benefits and customization. ¹ Read more about Rake at http://rake.rubyforge.org/ ² Get information on Lookout-Rake at http://disu.se/software/lookout-rake/ § API Lookout comes with an API¹ that let’s you create things such as new expected values, difference reports for your types, and so on. ¹ See http://disu.se/software/lookout/api/ § Interface Design The default output of Lookout can Spartanly be described as Spartan. If no errors or failures occur, no output is generated. This is unconventional, as unit testing frameworks tend to dump a lot of information on the user, concerning things such as progress, test count summaries, and flamboyantly colored text telling you that your tests passed. None of this output is needed. Your tests should run fast enough to not require progress reports. The lack of output provides you with the same amount of information as reporting success. Test count summaries are only useful if you’re worried that your tests aren’t being run, but if you worry about that, then providing such output doesn’t really help. Testing your tests requires something beyond reporting some arbitrary count that you would have to verify by hand anyway. When errors or failures do occur, however, the relevant information is output in a format that can easily be parsed by an ‹'errorformat'› for Vim or with {Compilation Mode}¹ for Emacs². Diffs are generated for Strings, Arrays, Hashes, and I/O. ¹ Read up on Compilation mode for Emacs at http://www.emacswiki.org/emacs/CompilationMode ² Visit The GNU Foundation’s Emacs’ software page at http://www.gnu.org/software/emacs/ § External Design Let’s now look at some of the points made in the introduction in greater detail. Lookout only allows you to set one expectation per test. If you’re testing behavior with a reception expectation, then only one method-invocation expectation can be set. If you’re testing state, then only one result can be verified. It may seem like this would cause unnecessary duplication between tests. While this is certainly a possibility, when you actually begin to try to avoid such duplication you find that you often do so by improving your interfaces. This kind of restriction tends to encourage the use of value objects, which are easy to test, and more focused objects, which require simpler tests, as they have less behavior to test, per method. By keeping your interfaces focused you’re also keeping your tests focused. Keeping your tests focused improves, in itself, test isolation, but let’s look at something that hinders it: setup and tear-down methods. Most unit testing frameworks encourage test fragmentation by providing setup and tear-down methods. Setup methods create objects and, perhaps, just their behavior for a set of tests. This means that you have to look in two places to figure out what’s being done in a test. This may work fine for few methods with simple set-ups, but makes things complicated when the number of tests increases and the set-up is complex. Often, each test further adjusts the previously set-up object before performing any verifications, further complicating the process of figuring out what state an object has in a given test. Tear-down methods clean up after tests, perhaps by removing records from a database or deleting files from the file-system. The duplication that setup methods and tear-down methods hope to remove is better avoided by improving your interfaces. This can be done by providing better set-up methods for your objects and using idioms such as {Resource Acquisition Is Initialization}¹ for guaranteed clean-up, test or no test. By not using setup and tear-down methods we keep everything pertinent to a test in the test itself, thus improving test isolation. (You also won’t {slow down your tests}² by keeping unnecessary state.) Most unit test frameworks also allow you to create arbitrary test helper methods. Lookout doesn’t. The same rationale as that that has been crystallized in the preceding paragraphs applies. If you need helpers you’re interface isn’t good enough. It really is as simple as that. To clarify: there’s nothing inherently wrong with test helper methods, but they should be general enough that they reside in their own library. The support for mocks in Lookout is provided through a set of test helper methods that make it easier to create mocks than it would have been without them. Lookout-rack³ is another example of a library providing test helper methods (well, one method, actually) that are very useful in testing web applications that use Rack⁴. A final point at which some unit test frameworks try to fragment tests further is documentation. These frameworks provide ways of describing the whats and hows of what’s being tested, the rationale being that this will provide documentation of both the test and the code being tested. Describing how a stack data structure is meant to work is a common example. A stack is, however, a rather simple data structure, so such a description provides little, if any, additional information that can’t be extracted from the implementation and its tests themselves. The implementation and its tests is, in fact, its own best documentation. Taking the points made in the previous paragraphs into account, we should already have simple, self-describing, interfaces that have easily understood tests associated with them. Rationales for the use of a given data structure or system-design design documentation is better suited in separate documentation focused at describing exactly those issues. ¹ Read the Wikipedia entry for Resource Acquisition Is Initialization at http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization ² Read how 37signals had problems with slow Test::Unit tests at http://37signals.com/svn/posts/2742-the-road-to-faster-tests/ ³ Visit the Lookout-rack home page at http://disu.se/software/lookout-rack/ ⁴ Visit the Rack Rubyforge project page at http://rack.rubyforge.org/ § Internal Design The internal design of Lookout has had a couple of goals. • As few external dependencies as possible • As few internal dependencies as possible • Internal extensibility provides external extensibility • As fast load times as possible • As high a ratio of value objects to mutable objects as possible • Each object must have a simple, obvious name • Use mix-ins, not inheritance for shared behavior • As few responsibilities per object as possible • Optimizing for speed can only be done when you have all the facts § External Dependencies Lookout used to depend on Mocha for mocks and stubs. While benchmarking I noticed that a method in Mocha was taking up more than 300 percent of the runtime. It turned out that Mocha’s method for cleaning up back-traces generated when a mock failed was doing something incredibly stupid: backtrace.reject{ |l| Regexp.new(@lib).match(File.expand_path(l)) } Here ‹@lib› is a ‹String› containing the path to the lib sub-directory in the Mocha installation directory. I reported it, provided a patch five days later, then waited. Nothing happened. {254 days later}¹, according to {Wolfram Alpha}², half of my patch was, apparently – I say “apparently”, as I received no notification – applied. By that time I had replaced the whole mocking-and-stubbing subsystem and dropped the dependency. Many Ruby developers claim that Ruby and its gems are too fast-moving for normal package-managing systems to keep up. This is testament to the fact that this isn’t the case and that the real problem is instead related to sloppy practices. Please note that I don’t want to single out the Mocha library nor its developers. I only want to provide an example where relying on external dependencies can be “considered harmful”. ¹ See the Wolfram Alpha calculation at http://www.wolframalpha.com/input/?i=days+between+march+17%2C+2010+and+november+26%2C+2010 ² Check out the Wolfram Alpha computational knowledge engine at http://www.wolframalpha.com/ § Internal Dependencies Lookout has been designed so as to keep each subsystem independent of any other. The diff subsystem is, for example, completely decoupled from any other part of the system as a whole and could be moved into its own library at a time where that would be of interest to anyone. What’s perhaps more interesting is that the diff subsystem is itself very modular. The data passes through a set of filters that depends on what kind of diff has been requested, each filter yielding modified data as it receives it. If you want to read some rather functional Ruby I can highly recommend looking at the code in the ‹lib/lookout/diff› directory. This lookout on the design of the library also makes it easy to extend Lookout. Lookout-rack was, for example, written in about four hours and about 5 of those 240 minutes were spent on setting up the interface between the two. § Optimizing For Speed The following paragraph is perhaps a bit personal, but might be interesting nonetheless. I’ve always worried about speed. The original Expectations library used ‹extend› a lot to add new behavior to objects. Expectations, for example, used to hold the result of their execution (what we now term “evaluation”) by being extended by a module representing success, failure, or error. For the longest time I used this same method, worrying about the increased performance cost that creating new objects for results would incur. I finally came to a point where I felt that the code was so simple and clean that rewriting this part of the code for a benchmark wouldn’t take more than perhaps ten minutes. Well, ten minutes later I had my results and they confirmed that creating new objects wasn’t harming performance. I was very pleased. § Naming I hate low lines (underscores). I try to avoid them in method names and I always avoid them in file names. Since the current “best practice” in the Ruby community is to put ‹BeginEndStorage› in a file called ‹begin_end_storage.rb›, I only name constants using a single noun. This has had the added benefit that classes seem to have acquired less behavior, as using a single noun doesn’t allow you to tack on additional behavior without questioning if it’s really appropriate to do so, given the rather limited range of interpretation for that noun. It also seems to encourage the creation of value objects, as something named ‹Range› feels a lot more like a value than ‹BeginEndStorage›. (To reach object-oriented-programming Nirvana you must achieve complete value.) § News § 3.0.0 The ‹xml› expectation has been dropped. It wasn’t documented, didn’t suit very many use cases, and can be better implemented by an external library. The ‹arg› argument matcher for mock method arguments has been removed, as it didn’t provide any benefit over using Object. The ‹#yield› and ‹#each› methods on stub and mock methods have been removed. They were slightly weird and their use case can be implemented using block parameters instead. The ‹stub› method inside ‹expect› blocks now stubs out the methods during the execution of a provided block instead of during the execution of the whole except block. When a mock method is called too many times, this is reported immediately, with a full backtrace. This makes it easier to pin down what’s wrong with the code. Query expectations were added. Explicit query expectations were added. Fluent boolean expectations, for example, ‹expect nil.to.be.nil?› have been replaced by query expectations (‹expect :nil? do nil end›) and explicit query expectations (‹expect result.to.be.nil? do nil end›). This was done to discourage creating objects as the expected value and creating objects that change during the course of the test. The ‹literal› expectation was added. Equality (‹#==›) is now checked before “caseity” (‹#===›) for modules, ranges, and regular expressions to match the documentation. § Financing Currently, most of my time is spent at my day job and in my rather busy private life. Please motivate me to spend time on this piece of software by donating some of your money to this project. Yeah, I realize that requesting money to develop software is a bit, well, capitalistic of me. But please realize that I live in a capitalistic society and I need money to have other people give me the things that I need to continue living under the rules of said society. So, if you feel that this piece of software has helped you out enough to warrant a reward, please PayPal a donation to now@disu.se¹. Thanks! Your support won’t go unnoticed! ¹ Send a donation: https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=now%40disu%2ese&item_name=Lookout § Reporting Bugs Please report any bugs that you encounter to the {issue tracker}¹. ¹ See https://github.com/now/lookout/issues § Contributors Contributors to the original expectations codebase are mentioned there. We hope no one on that list feels left out of this list. Please {let us know}¹ if you do. • Nikolai Weibull ¹ Add an issue to the Lookout issue tracker at https://github.com/now/lookout/issues § Licensing Lookout is free software: you may redistribute it and/or modify it under the terms of the {GNU Lesser General Public License, version 3}¹ or later², as published by the {Free Software Foundation}³. ¹ See http://disu.se/licenses/lgpl-3.0/ ² See http://gnu.org/licenses/ ³ See http://fsf.org/
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Popularity
0.0
No commit activity in last 3 years
No release in over 3 years
# COM # COM is an object-oriented wrapper around WIN32OLE. COM makes it easy to add behavior to WIN32OLE objects, making them easier to work with from Ruby. ## Usage ## Using COM is rather straightforward. There’s basically four concepts to keep track of: 1. COM objects 2. Instantiable COM objects 3. COM events 4. COM errors Let’s look at each concept separately, using the following example as a base. module Word end class Word::Application < COM::Instantiable def without_interaction with_properties('displayalerts' => Word::WdAlertsNone){ yield } end def documents Word::Documents.new(com.documents) end def quit(saving = Word::WdDoNotSaveChanges, *args) com.quit saving, *args end end ### COM Objects ### A COM::Object is a wrapper around a COM object. It provides error specialization, which is discussed later and a few utility methods. You typically use it to wrap COM objects that are returned by COM methods. If we take the example given in the introduction, Word::Documents is a good candidate: class Word::Documents < COM::Object DefaultOpenOptions = { 'confirmconversions' => false, 'readonly' => true, 'addtorecentfiles' => false, 'visible' => false }.freeze def open(path, options = {}) options = DefaultOpenOptions.merge(options) options['filename'] = Pathname(path).to_com Word::Document.new(com.open(options)) end end Here we override the #open method to be a bit easier to use, providing sane defaults for COM interaction. Worth noting is the use of the #com method to access the actual COM object to invoke the #open method on it. Also note that Word::Document is also a COM::Object. COM::Object provides a convenience method called #with_properties, which is used in the #without_interaction method above. It lets you set properties on the COM::Object during the duration of a block, restoring them after it exits (successfully or with an error). ### Instantiable COM Objects ### Instantiable COM objects are COM objects that we can connect to and that can be created. The Word::Application object can, for example, be created. Instantiable COM objects should inherit from COM::Instantiable. Instantiable COM objects can be told what program ID to use, whether or not to allow connecting to an already running object, and to load its associated constants upon creation. The program ID is used to determine what instantiable COM object to connect to. By default the name of the COM::Instantiable class’ name is used, taking the last two double-colon-separated components and joining them with a dot. For Word::Application, the program ID is “Word.Application”. The program ID can be set by using the .program_id method: class IDontCare::ForConventions < COM::Instantiable program_id 'Word.Application' end The program ID can be accessed with the same method: Word::Application.program_id # ⇒ 'Word.Application' Connecting to an already running COM object is not done by default, but is sometimes desirable: the COM object might take a long time to create, or some common state needs to be accessed. If the default for a certain instantiable COM object should be to connect, this can be done using the .connect method: class Word::Application < COM::Instantiable connect end If no running COM object is available, then a new COM object will be created in its stead. Whether or not a class uses the connection method can be queried with the .connect? method: Word::Application.connect? # ⇒ true Whether or not to load constants associated with an instantiable COM object is set with the .constants method: class Word::Application < COM::Instantiable constants true end and can similarly be checked: Word::Application.constants? # ⇒ true Constants are loaded by default. When an instance of the instantiable COM object is created, a check is run to see if constants should be loaded and whether or not they already have been loaded. If they should be loaded and they haven’t already been loaded, they’re, you guessed it, loaded. The constants are added to the module containing the COM::Instantiable. Thus, for Word::Application, the Word module will contain all the constants. Whether or not the constants have already been loaded can be checked with .constants_loaded?: Word::Application.constants_loaded # ⇒ false That concludes the class-level methods. Let’s begin with the #connected? method among the instance-level methods. This method queries whether or not this instance connected to an already running COM object: Word::Application.new.connected? # ⇒ false This can be very important in determining how shutdown of a COM object should be done. If you connected to an already COM object it might be foolish to shut it down if someone else is using it. The #initialize method takes a couple of options: * connect: whether or not to connect to a running instance * constants: whether or not to load constants These options will, when given, override the class-level defaults. ### Events ### COM events are easily dealt with: class Word::Application < COM::Instantiable def initialize(options = {}) super @events = COM::Events.new(com, 'ApplicationEvents', 'OnQuit') end def quit(saving = Word::WdDoNotSaveChanges, *args) @events.observe('OnQuit', proc{ com.quit saving, *args }) do yield if block_given? end end end To tell you the truth this API sucks and will most likely be rewritten. The reason that it is the way it is is that WIN32OLE, which COM wraps, sucks. It’s event API is horrid and the implementation is buggy. It will keep every registered event block in memory for ever, freeing neither the blocks nor the COM objects that yield the events. ### Errors ### All errors generated by COM methods descend from COM::Error, except for those cases where a Ruby error already exists. The following HRESULT error codes are turned into Ruby errors: HRESULT Error Code | Error Class -------------------|------------ 0x80004001 | NotImplementedError 0x80020005 | TypeError 0x80020006 | NoMethodError 0x8002000e | ArgumentError 0x800401e4 | ArgumentError There are also a couple of other HRESULT error codes that are turned into more specific errors than COM::Error: HRESULT Error Code | Error Class -------------------|------------ 0x80020003 | MemberNotFoundError 0x800401e3 | OperationUnavailableError Finally, when a method results in any other error, a COM::MethodInvocationError will be raised, which can be queried for the specifics, specifically #message, #method, #server, #code, #hresult_code, and #hresult_message. ### Pathname ### The Pathname object receives an additional method, #to_com. This method is useful for when you want to pass a Pathname object to a COM method. Simply call #to_com to turn it into a String of the right encoding for COM: Word::Application.new.documents.open(Pathname('a.docx').to_com) # ⇒ Word::Document ## Installation ## Install COM with % gem install com ## License ## You may use, copy and redistribute this library under the same [terms][1] as Ruby itself. [1]: http://www.ruby-lang.org/en/LICENSE.txt ## Contributors ## * Nikolai Weibull
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
0.0
Repository is gone
No release in over 3 years
== PintosCheck -- Auto Pintos Checker to Save the Day == == Functionalities == The functionality of this simple script is to download pintos homework assignments from the mail inbox and then run through all the desired tests and finally generate reports in plain text or html formats, all automatically. == Requirements For Running PintosCheck == Since all the scripts are written in ruby, PintosCheck require ruby installed on the system. I use ruby 1.8.7 for development, but ruby 1.9.* versions are expected to function as well. However, ruby 1.8.6 and lower versions are not supported. For information of downloading and installing ruby, see http://www.ruby-lang.org/en/downloads/. In addition to ruby itself, RubyGems 1.3.* is also required because it hosts the installation source for this project and almost all other ruby projects as well. To download or update RubyGems, please go to http://gemcutter.org/pages/download for more information. == Installation == Once you have all the requirements on your system, it's really easy to install PintosCheck. In the UNIX shell or Windows command line environment, type the following command(sudo if needed): gem install pintoscheck --include-dependencies Go grab a cup of coffee, and PintosCheck will automatically download and install itself onto the system. To check the installation, type 'ptschk --version', and if something like 'PintosCheck 0.1.0' pops up then you're green to go! == Finally, how do I check my students' pintos homework? == This project ships with a 'ptschk' command tool. This tool needs a task configuration file to actually do everything. The configuration file is in YAML format, which is basically a recursive key-value pair representation. If you're using PintosCheck for the first time, there's a very nice command line option to generate the skeleton for you. Just run 'ptschk init my_first_task.config' and a file named 'my_first_task.config' will be generated for you. Inside this file there is a set of the minimal options for the task to run properly, and you just have to fill in what you need. After you set up your configuration file, run 'ptschk run my_first_task.config' and the tasks will kick off immediately, and after a while the report will be generated. A detailed configuration options for advanced task setup will be available in production release of this project.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Popularity
0.0
No release in over 3 years
$Id: README.txt 204 2010-11-30 02:20:04Z pwilkins $ sm-transcript reads results of SLS processing and produces transcripts for the SpokenMedia browser. For each file in the source folder whose extension matches the source type, a file of destination type is created in the destination folder. All of these parameters have default values. Note: Examples of the commands you enter in the terminal are for *nix. The command prompt in the examples is: felix$ <command line> If you are a Windows user, make the usual adjustments. Requirements: sm-transcript is written in Ruby and packaged as a RubyGem. Since Ruby is not a compiled language, you will need to have Ruby installed on your machine to run sm-transcript. You can determine if Ruby is installed by typing "ruby -v" at a terminal prompt. It should return the version of Ruby that is installed. If Ruby is not installed on your machine, navigate to http://www.ruby-lang.org/ and follow the installation instructions. sm-transcript was developed using Ruby 1.8. Other Ruby versions have not been tested as of this release. Installation: You can get sm-transcript as either a RubyGem or as source from svn. The preferred way to install this package is as a Rubygem. You can download and install the gem with this command: felix$ sudo gem install [--verbose] sm-transcript This command downloads the most recent version of the gem from rubygems.org and makes it active. Previous versions of the gem remain installed, but are deactivated. You must use "sudo" to properly install the gem. If you execute "gem install" (omitting the "sudo") the gem is installed in your home gem repository and it isn't in your path without additional configuration. Note: You need sudo privileges to run the command as written. If you can't sudo, then you can install it locally and will need some additional configuration. Contact me (or your local Ruby wizard) for assistance. The executable is now in your path. You can cleanly uninstall the gem with this command: felix$ sudo gem uninstall sm-transcript If you have access to our svn repository, you are welcome to check out the code. Be warned that the trunk tip is not necessarily stable. It changes frequently as enhancements (and bug fixes) are added. (note that the 'smb_transcript' in the command line below is not a typo.) svn co svn+ssh://svn.mit.edu/oeit-tsa/SMB/smb_transcript/trunk sm_transcript build the gem by running this command from the directory you installed the source. This is what it looks like on my machine: felix$ rake gem The gem will be built and put in ./pkg You can now use the gem installation instructions above. Using the App: Run with no command line parameters, the app reads *.wrd files out of ./results and writes *.t1.html files to ./transcripts. These directories are relative to where sm_transcript is called. Note: destination files are overwritten without a warning prompt. If you want to preserve an existing output file, rename it before running the app again. For example, run the app by navigating to the bin folder and enter projects/sm_transcript/bin felix$ sm_transcript This command run from this folder will read *.wrd files from bin/results and write *-t1.html to bin/transcripts. Usage: sm_transcript [options] --srcdir PATH Read files from this folder (Default: ./results) --destdir PATH Write files to this folder (Default: ./transcripts) --srctype wrd | seg | txt | ttml | srt Kind of file to process (Default: wrd) --desttype html | ttml | datajs | json Kind of file to output (Default: html) -h, --help Show this message There is a serious gotch'a in specifying the srctype parameter: it must match the case of the file extension that you're processing. This means that if the srt files that you are processing have the extension .SRT, then you must specify the srctype as "SRT". Pretty lame, I know. I will update the gem with a fix shortly. My apologies until then. Troubleshooting: sm-transcript requires additional gems to operate. The RubyGem installation should install dependencies automatically, but when it doesn't, you get an error that includes ... no such file to load -- builder (LoadError) in the first few lines when you run sm-transcript, the problem is a missing dependent gem. (the error above indicates that the Builder gem is missing.) Try installing the missing gem. For the error above, the command looks like this on my computer: felix$ sudo gem install builder See "Required Gems" below for more information. A warning message such as: "WARNING: Nokogiri was built against LibXML version 2.7.6, but has dynamically loaded 2.7.7"" may be safely ignored. If you continue to have trouble, feel free to contact me. Upgrading: You can easily upgrade by simply executing the same command you used to install the gem. Running install again will add the newer version and make it active. By default the most recent version is used, but older versions are still available, simply inactive. If are using svn, you should already know what to do. Required Gems: builder - create structured data, such as XML extensions - added for the 'require_relative' command. (To get this command in Ruby 1.8 you need to install this gem, for Ruby 1.9 the command is already part of the core.) htmlentities - html parsing json - create JSON structured data nokogiri - xml parsing library optparse - option parsing of command line ostruct - open data structures ppcommand - pp is a pretty printer. It is used only for debugging rake - make for Ruby rubygems - support for gems (shouldn't be needed for Ruby 1.9) shoulda - enhancement for Test::Unit This command installs gems on OSX and Linux: felix$ sudo gem install <gem name> I recommend running the following command to update to latest version of rubygems before loading new gems. felix$ sudo gem update --system Unit Tests: You may run all unit tests by navigating to the test folder and running rake with no parameters (the default rake task runs all tests). On my computer, it looks like this: projects/sm_transcript/test felix$ rake Release Notes: Initial Version - runs under Ruby 1.8.x. version 0.0.4 - fixes bug when processing .WRD files with CRLF line endings. version 0.0.5 - removed due to posting error version 0.0.6 - added srctype of ttml and desttype of json, fixed bug where beginning time of word was actually for previous word. version 0.0.7 - added srt as srctype version 0.0.8 - fixed bug that dropped last phrase from transcripts version 1.0.0 - declared this version 1.0.0 to conform more closely with gem numbering conventions. All tests run successfully. To Do: - specify individual files for processing rather than folders - fix bug in srt processing: can't read Creole srt content. - allow user to modify the "t1" file extension for addition languages of the same transcript. - update code to run under Ruby 1.9
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Popularity
0.0
No release in over 3 years
ALPHA Alert -- just uploaded initial release. Linux inotify is a means to receive events describing file system activity (create, modify, delete, close, etc). Sinotify was derived from aredridel's package (http://raa.ruby-lang.org/project/ruby-inotify/), with the addition of Paul Boon's tweak for making the event_check thread more polite (see http://www.mindbucket.com/2009/02/24/ruby-daemons-verifying-good-behavior/) In sinotify, the classes Sinotify::PrimNotifier and Sinotify::PrimEvent provide a low level wrapper to inotify, with the ability to establish 'watches' and then listen for inotify events using one of inotify's synchronous event loops, and providing access to the events' masks (see 'man inotify' for details). Sinotify::PrimEvent class adds a little semantic sugar to the event in to the form of 'etypes', which are just ruby symbols that describe the event mask. If the event has a raw mask of (DELETE_SELF & IS_DIR), then the etypes array would be [:delete_self, :is_dir]. In addition to the 'straight' wrapper in inotify, sinotify provides an asynchronous implementation of the 'observer pattern' for notification. In other words, Sinotify::Notifier listens in the background for inotify events, adapting them into instances of Sinotify::Event as they come in and immediately placing them in a concurrent queue, from which they are 'announced' to 'subscribers' of the event. [Sinotify uses the 'cosell' implementation of the Announcements event notification framework, hence the terminology 'subscribe' and 'announce' rather then 'listen' and 'trigger' used in the standard event observer pattern. See the 'cosell' package on github for details.] A variety of 'knobs' are provided for controlling the behavior of the notifier: whether a watch should apply to a single directory or should recurse into subdirectores, how fast it should broadcast queued events, etc (see Sinotify::Notifier, and the example in the synopsis section below). An event 'spy' can also be setup to log all Sinotify::PrimEvents and Sinotify::Events. Sinotify::Event simplifies inotify's muddled event model, sending events only for those files/directories that have changed. That's not to say you can't setup a notifier that recurses into subdirectories, just that any individual event will apply to a single file, and not to its children. Also, event types are identified using words (in the form of ruby :symbols) instead of inotify's event masks. See Sinotify::Event for more explanation. The README for inotify: http://www.kernel.org/pub/linux/kernel/people/rml/inotify/README Selected quotes from the README for inotify: * "Rumor is that the 'd' in 'dnotify' does not stand for 'directory' but for 'suck.'" * "The 'i' in inotify does not stand for 'suck' but for 'inode' -- the logical choice since inotify is inode-based." (The 's' in 'sinotify' does in fact stand for 'suck.')
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Popularity
0.0
No release in over 3 years
ALPHA Alert -- just uploaded initial release. Linux inotify is a means to receive events describing file system activity (create, modify, delete, close, etc). Sinotify was derived from aredridel's package (http://raa.ruby-lang.org/project/ruby-inotify/), with the addition of Paul Boon's tweak for making the event_check thread more polite (see http://www.mindbucket.com/2009/02/24/ruby-daemons-verifying-good-behavior/) In sinotify, the classes Sinotify::PrimNotifier and Sinotify::PrimEvent provide a low level wrapper to inotify, with the ability to establish 'watches' and then listen for inotify events using one of inotify's synchronous event loops, and providing access to the events' masks (see 'man inotify' for details). Sinotify::PrimEvent class adds a little semantic sugar to the event in to the form of 'etypes', which are just ruby symbols that describe the event mask. If the event has a raw mask of (DELETE_SELF &amp; IS_DIR), then the etypes array would be [:delete_self, :is_dir]. In addition to the 'straight' wrapper in inotify, sinotify provides an asynchronous implementation of the 'observer pattern' for notification. In other words, Sinotify::Notifier listens in the background for inotify events, adapting them into instances of Sinotify::Event as they come in and immediately placing them in a concurrent queue, from which they are 'announced' to 'subscribers' of the event. [Sinotify uses the 'cosell' implementation of the Announcements event notification framework, hence the terminology 'subscribe' and 'announce' rather then 'listen' and 'trigger' used in the standard event observer pattern. See the 'cosell' package on github for details.] A variety of 'knobs' are provided for controlling the behavior of the notifier: whether a watch should apply to a single directory or should recurse into subdirectores, how fast it should broadcast queued events, etc (see Sinotify::Notifier, and the example in the synopsis section below). An event 'spy' can also be setup to log all Sinotify::PrimEvents and Sinotify::Events. Sinotify::Event simplifies inotify's muddled event model, sending events only for those files/directories that have changed. That's not to say you can't setup a notifier that recurses into subdirectories, just that any individual event will apply to a single file, and not to its children. Also, event types are identified using words (in the form of ruby :symbols) instead of inotify's event masks. See Sinotify::Event for more explanation. The README for inotify: http://www.kernel.org/pub/linux/kernel/people/rml/inotify/README Selected quotes from the README for inotify: * "Rumor is that the 'd' in 'dnotify' does not stand for 'directory' but for 'suck.'" * "The 'i' in inotify does not stand for 'suck' but for 'inode' -- the logical choice since inotify is inode-based." (The 's' in 'sinotify' does in fact stand for 'suck.')
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Popularity
0.0
No release in over 3 years
This is an experimental branch that implements a connection pool of Net::HTTP objects instead of a connection/thread. C/T is fine if you're only using your http threads to make connections but if you use them in child threads then I suspect you will have a thread memory leak. Also, I want to see if I get less connection resets if the most recently used connection is always returned. Also added a :force_retry option that if set to true will retry POST requests as well as idempotent requests. This branch is currently incompatible with the master branch in the following ways: * It doesn't allow you to recreate the Net::HTTP::Persistent object on the fly. This is possible in the master version since all the data is kept in thread local storage. For this version, you should probably create a class instance of the object and use that in your instance methods. * It uses a hash in the initialize method. This was easier for me as I use a HashWithIndifferentAccess created from a YAML file to define my options. This should probably be modified to check the arguments to achieve backwards compatibility. * The method shutdown is unimplemented as I wasn't sure how I should implement it and I don't need it as I do a graceful shutdown from nginx to finish up my connections. For connection issues, I completely recreate a new Net::HTTP instance. I was running into an issue which I suspect is a JRuby bug where an SSL connection that times out would leave the ssl context in a frozen state which would then make that connection unusable so each time that thread handled a connection a 500 error with the exception "TypeError: can't modify frozen". I think Joseph West's fork resolves this issue but I'm paranoid so I recreate the object. Compatibility with the master version could probably be achieved by creating a Strategy wrapper class for GenePool and a separate strategy class with the connection/thread implementation.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Popularity
0.0
No commit activity in last 3 years
No release in over 3 years
# Rake::ToolkitProgram Create toolkit programs easily with `Rake` and `OptionParser` syntax. Bash completions and usage help are baked in. ## Installation Add this line to your application's Gemfile: ```ruby gem 'rake-toolkit_program' ``` And then execute: $ bundle Or install it yourself as: $ gem install rake-toolkit_program ## Quickstart * Shebang it up (in a file named `awesome_tool.rb`) ```ruby #!/usr/bin/env ruby ``` * Require the library ```ruby require 'rake/toolkit_program' ``` * Make your life easier ```ruby Program = Rake::ToolkitProgram ``` * Define your command tasks ```ruby Program.command_tasks do desc "Build it" task 'build' do # Ruby code here end desc "Test it" task 'test' => ['build'] do # Rake syntax ↑↑↑↑↑↑↑ for dependencies # Ruby code here end end ``` You can use `Program.args` in your tasks to access the other arguments on the command line. For argument parsing integrated into the help provided by the program, see the use of `Rake::Task(Rake::ToolkitProgram::TaskExt)#parse_args` below. * Wire the mainline ```ruby Program.run(on_error: :exit_program!) if $0 == __FILE__ ``` * In the shell, prepare to run the program (UNIX/Linux systems only) ```console $ chmod +x awesome_tool.rb $ ./awesome_tool.rb --install-completions Completions installed in /home/rtweeks/.bashrc Source /home/rtweeks/.bash-complete/awesome_tool.rb-completions for immediate availability. $ source /home/rtweeks/.bash-complete/awesome_tool.rb-completions ``` * Ask for help ```console $ ./awesome_tool.rb help *** ./awesome_tool.rb Toolkit Program *** . . . ``` ## Usage Let's look at a short sample toolkit program -- put this in `awesome.rb`: ```ruby #!/usr/bin/env ruby require 'rake/toolkit_program' require 'ostruct' ToolkitProgram = Rake::ToolkitProgram ToolkitProgram.title = "My Awesome Toolkit of Awesome" ToolkitProgram.command_tasks do desc <<-END_DESC.dedent Fooing myself I'm not sure what I'm doing, but I'm definitely fooing! END_DESC task :foo do a = ToolkitProgram.args puts "I'm fooed#{' on a ' if a.implement}#{a.implement}" end.parse_args(into: OpenStruct.new) do |parser, args| parser.no_positional_args! parser.on('-i', '--implement IMPLEMENT', 'An implement on which to be fooed') do |val| args.implement = val end end end if __FILE__ == $0 ToolkitProgram.run(on_error: :exit_program!) end ``` Make sure to `chmod +x awesome.rb`! What does this support? $ ./awesome.rb foo I'm fooed $ ./awesome.rb --help *** My Awesome Toolkit of Awesome *** Usage: ./awesome.rb COMMAND [OPTION ...] Avaliable options vary depending on the command given. For details of a particular command, use: ./awesome.rb help COMMAND Commands: foo Fooing myself help Show a list of commands or details of one command Use help COMMAND to get more help on a specific command. $ ./awesome.rb help foo *** My Awesome Toolkit of Awesome *** Usage: ./awesome.rb foo [OPTION ...] Fooing myself I'm not sure what I'm doing, but I'm definitely fooing! Options: -i, --implement IMPLEMENT An implement on which to be fooed $ ./awesome.rb --install-completions Completions installed in /home/rtweeks/.bashrc Source /home/rtweeks/.bash-complete/awesome.rb-completions for immediate availability. $ source /home/rtweeks/.bash-complete/awesome.rb-completions $ ./awesome.rb <tab><tab> foo help $ ./awesome.rb f<tab> ↳ ./awesome.rb foo $ ./awesome.rb foo <tab> ↳ ./awesome.rb foo -- $ ./awesome.rb foo --<tab><tab> --help --implement $ ./awesome.rb foo --i<tab> ↳ ./awesome.rb foo --implement $ ./awesome.rb foo --implement <tab><tab> --help awesome.rb $ ./awesome.rb foo --implement spoon I'm fooed on a spoon ### Defining Toolkit Commands Just define tasks in the block of `Rake::ToolkitProgram.command_tasks` with `task` (i.e. `Rake::DSL#task`). If `desc` is used to provide a description, the task will become visible in help and completions. When a command task is initially defined, positional arguments to the command are available as an `Array` through `Rake::ToolkitProgram.args`. ### Option Parsing This gem extends `Rake::Task` with a `#parse_args` method that creates a `Rake::ToolkitProgram::CommandOptionParser` (derived from the standard library's `OptionParser`) and an argument accumulator and `yield`s them to its block. * The arguments accumulated through the `Rake::ToolkitProgram::CommandOptionParser` are available to the task in `Rake::ToolkitProgram.args`, replacing the normal `Array` of positional arguments. * Use the `into:` keyword of `#parse_args` to provide a custom argument accumulator object for the associated command. The default argument accumulator constructor can be defined with `Rake::ToolkitProgram.default_parsed_args`. Without either of these, the default accumulator is a `Hash`. * Options defined using `OptionParser#on` (or any of the variants) will print in the help for the associated command. ### Positional Arguments Accessing positional arguments given after the command name depends on whether or not `Rake::Task(Rake::ToolkitProgram::TaskExt)#parse_args` has been called on the command task. If this method is not called, positional arguments will be an `Array` accessible through `Rake::ToolkitProgram.args`. When `Rake::Task(Rake::ToolkitProgram::TaskExt)#parse_args` is used: * `Rake::ToolkitProgram::CommandOptionParser#capture_positionals` can be used to define how positional arguments are accumulated. * If the argument accumulator is a `Hash`, the default (without calling this method) is to assign the `Array` of positional arguments to the `nil` key of the `Hash`. * For other types of accumulators, the positional arguments are only accessible if `Rake::ToolkitProgram::CommandOptionParser#capture_positionals` is used to define how they are captured. * If a block is given to this method, the block of the method will receive the `Array` of positional arguments. If it is passed an argument value, that value is used as the key under which to store the positional arguments if the argument accumulator is a `Hash`. * `Rake::ToolkitProgram::CommandOptionParser#expect_positional_cardinality` can be used to set a rule for the count of positional arguments. This will affect the _usage_ presented in the help for the associated command. * `Rake::ToolkitProgram::CommandOptionParser#map_positional_args` may be used to transform (or otherwise process) positional arguments one at a time and in the context of options and/or arguments appearing earlier on the command line. ### Convenience Methods * `Rake::Task(Rake::ToolkitProgram::TaskExt)#prohibit_args` is a quick way, for commands that accept no options or positional arguments, to declare this so the help and bash completions reflect this. It is equivalent to using `#parse_args` and telling the parser `parser.expect_positional_cardinality(0)`. * `Rake::ToolkitProgram::CommandOptionParser#no_positional_args!` is a shortcut for calling `#expect_positional_cardinality(0)` on the same object. * `Rake::Task(Rake::ToolkitProgram::TaskExt)#invalid_args!` and `Rake::ToolkitProgram::CommandOptionParser#invalid_args!` are convenient ways to raise `Rake::ToolkitProgram::InvalidCommandLine` with a message. ## OptionParser in Rubies Before and After v2.4 The `OptionParser` class was extended in Ruby 2.4 to simplify capturing options into a `Hash` or other container implementing `#[]=` in a similar way. This gem supports that, but it means that behavior varies somewhat between the pre-2.4 era and the 2.4+ era. To have consistent behavior across that version change, the recommendation is to use a `Struct`, `OpenStruct`, or custom class to hold program options rather than `Hash`. ## Development After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment. To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org). To run the tests, use `rake`, `rake test`, or `rspec spec`. Tests can only be run on systems that support `Kernel#fork`, as this is used to present a pristine and isolated environment for setting up the tool. If run using Ruby 2.3 or earlier, some tests will be pending because functionality expects Ruby 2.4's `OptionParser`. ## Contributing Bug reports and pull requests are welcome on GitHub at https://github.com/PayTrace/rake-toolkit_program. For further details on contributing, see [CONTRIBUTING.md](./CONTRIBUTING.md).
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
0.0
No release in over 3 years
The code to check for the iPhone user agent is from http://developer.apple.com. This doesn't have any dependencies. - in app/controllers/application.rb require 'is_it_iphone' class ApplicationController &lt; ActionController::Base include IsItIPhone before_filter :adjust_format_for_iphone # Always show iPhone views end You will have these functions: iphone_user_agent? Returns true if the user agent is an iPhone. (as spec'ed on http://developer.apple.com) iphone_request? Returns true if the request came from an iPhone. Override being an iPhone with ?format=xxxx in the URL. adjust_format_for_iphone Call when you want to show iPhone views to iPhone users. Note: It is recommended by Apple that you default to showing your &quot;normal&quot; html page to iPhone users and allow them to choose if they want an iPhone version. With Rails 2.0, you can use its multiview capabilities by simply adding this to your app: - in config/initializers/mime_types.rb Mime::Type.register_alias &quot;text/html&quot;, :iphone Then, just create your views using suffices of iphone.erb instead of html.erb: index.iphone.erb show.iphone.erb etc. Note: you will probably want to use a Web library specific for iPhone applications. FWIW, I use Da shcode (in the iPhone SDK) to write and debug the iPhone application and then integrate it with my Rails project.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Popularity