Ruby scripts lack style
-
The SketchUp Ruby community needs to come up with a style sheet for writing scripts. I am not suggesting we tell proprietary or private script writers what style to use, NO i am speaking of all the open source and free ware scripts out there. These scripts belong to the SketchUp community as whole and we have a responsibility to make sure there bug free, and written in a style that not only teaches good coding practices but also promotes them. It's insane the amount of poor styles and inconstancies i see from script to script and EVEN inconsistencies within the same script! This style sheet will lay out the expected style for scripts to follow. Of course with Ruby's tim toady-ness we cannot make it perfect however we can do a lot to clean this god awful mess up!
Parenthesis around method arguments
One thing that really grinds my gears is the laziness of folks who refuse to wrap method arguments in parenthesis. I know the ruby language allows one to do this but its ugly, harder to read, and just exposes the author's laziness. Koala bears have an excuse to be lazy from eating those eucalyptus leaves all day, Ruby coders have no excuse!Indention Style
Another gear grinder (or jam'mer to exact) is the poor indention style, or lack there of. Yes Ruby does not force indention but you should use indention because it's more natural to read indented code. I personally perfer 4 space indention however ANY indention is better than NO indention. But whatever you do NEVER INDENT CODE IN THE WRONG PLACES AS THIS IS WORSE THAN NO INDENTION AT ALL! Indentions should only come at the start of a block body after one of these words (module, class, def, for, if, elsif, else... or after the "{")## good indention style ##
module namehere def self.method for x in collection if x == blah # do something with x else # jump off the golden gate end end end end
## Not so good indention style ##
module namehere def self.method for x in collection if x == blah # do something with x else # jump off the golden gate end end end end
## Horrible indention style ##
module namehere def self.method for x in collection if x == blah # do something with x else # jump off the golden gate end end end end
## You should be banned from coding style ##
module namehere def self.method for x in collection if x == blah # do something with x else # jump off the golden gate end end end end
And Never Ever mix indention widths within the same script. Picka a number of spaces and stick with it. Also never use tabs to indent because different editors use different distances for tab stops.
Loops (for verses each)
I personally prefer the for loop because i hate eyeball parsing "{" and "}". However if your loop is small enough to fit onto one line then by all means use the collection.each{...}. But again consistency is the key!Modules and Classes ...to indent or not to indent. That is the question!
I have said it before and i'll say it again... the module syntax is clutter and it would be more elegant to use the file as the module (like Python does) however thats a Ruby issue and we need to accept that for now. As my first example showed indenting the module code makes for nice readability however it does start getting dense. I am not against (and have myself done this) NOT indenting the module code body. However for classes the body should ALWAYS be indented!! Let me repeat that...HOWEVER FOR CLASSES THE BODY SHOULD ALWAYS BE INDENTED!!Documentation
People, you should always document your code at the very top. Start out with your license and then provide a detailed discription of what the code does and most importantly how the user will interface with the code. Please use complete sentences and proper punctuation and grammar. Code usage descriptions should take the same amount of effort as the code itself.Comments, wheres waldo?
Always include ample comments -- but never ever over comment as you can do more harm than good! Also remember that a poorly written comment will only serve to confuse the reader, it's better not comment at all than to confuse! Also as always use complete sentences and proper grammar and punctuation. If you have a very long comment break into logical paragraphs.I would like to hear input from all scripter's (new and old) about this subject. There is much much more to cover (i have not even mention naming conventions or repeated code, or multiple scripts that need to be combined) this only scratching the surface but we must start some where!
Thanks
-
Clean and organizes source code is of course a benefit for all. However, some parts are of personal preference. I for instance, like curly brackets. But I've begun to use
for in
loops more recently as in some cases they can be faster.For collaboration projects it is good to have a set style - but very few such projects exists. There is the CityGen and SKX projects, but they have been dormant for quite a while now. Don't think they've been on anyone's priority list - certainly not mine.
There was one by-comment there I reacted to:
@jessejames said:
[...] NO i am speaking of all the open source and free ware scripts out there. These scripts belong to the SketchUp community as whole[...]
Just to make clear - free doesn't mean it belongs to everyone. Still need permission from the author to redistribute free plugins, and source code if there are no explicit permission in the file itself.
-
@jessejames said:
It's insane the amount of poor styles and inconsitancies i see from script to script and EVEN inconsitencies within the same script!
A self referential example?
"Information-free" comments are a personal bugbear:
# loop over my_widgets for i in my_widgets
Utterly pointless. Well written code should read/scan easily. If you have to stop and re-read then it needs teasing out. Classic one is use of negated meaning in the name of variables. eg:
` notWriting = true
unless notWriting
...`makes you break the flow of reading code. Waste of time and those responsible should be flogged in a public place..or something.
Adam
-
@thomthom said:
Just to make clear - free doesn't mean it belongs to everyone. Still need permission from the author to redistribute free plugins, and source code if there are no explicit permission in the file itself.
Yes you are correct about this and there is a reason i used those words. The main reason is i cannot understand why someone would release free software and NOT open source it -- but make sure to read on so i can explain further because there are a few exceptions to this rule!
First of all if you create a script that uses real algorithms (i'm not talking about calling API methods ir iterating over some collection!) i talking about real algorithms that are creating an "above the normal" kind of script. Something new and wonderful, something not everyone here could write up in under a couple of hours. Then by all means release it under a license that protects the new ground you have conquered! But anyway i could go on for hours. Some folks here are here to suck up every dime they can and when the moneys gone they will move on to the next town to sell snake oil.
But lets get back on track here...
There are a lot of "open" and free scripts that need to be combined. There are lots of small tools that can be "grouped" into one script so these users don't have a Plugins menu 5 miles long. -
@adamb said:
@jessejames said:
It's insane the amount of poor styles and inconsitancies i see from script to script and EVEN inconsitencies within the same script!
A self referential example?
HaHa!, you got me however that was the beta 1 release of my post so i had not gotten a chance to debug. I just relased a bug fix version via the edit button
@adamb said:
[
"Information-free" comments are a personal bugbear:# loop over my_widgets for i in my_widgets
Utterly pointless.
I completely agree!
@adamb said:
Well written code should read/scan easily. If you have to stop and re-read then it needs teasing out. Classic one is use of negated meaning in the name of variables. eg:
` notWriting = true
unless notWriting
...`Again i completely agree. This style saves only a very few key stokes but induces levels of ambiguity that only MSDN and the US tax code can rival!
-
@jessejames said:
Yes you are correct about this and there is a reason i used those words. The main reason is i cannot understand why someone would release free software and NOT open source it -- but make sure to read on so i can explain further because there are a few exceptions to this rule!
My reason is that I have never bothered to look do closely at this whole open source concept. I know I use lots of software that are open source, but there are so many licenses out there to choose from - each with a long chuck of text with many clauses that it's hard to get an overview. And I also have no idea of what each license does - some let people use it commercial purposes etc. So I find it easier to just let people ask me and state their purpose.
@jessejames said:
There are lots of small tools that can be "grouped" into one script so these users don't have a Plugins menu 5 miles long.
@jessejames said:
Look we need to declare all out holy war against bad coding styles. We need to go through all the scripts at Ruby Library Depot, SketchUp scripts, and anywhere else we can get our grubby paws to, and re-write these abominations before too much damage is done
This just ain't going to happen. All these scripts are written by people on their own time. Most are written by non-professional like me. And many are written for a small specific purpose just to get the job done. I doubt there are many enthusiastic about re-working everything just for the sake of making the code pretty while not providing any advantage for end user. I certainly have no interest, and most importantly time, for such a huge task.
Whenever I pick up an old plugin of mine to add some new features I do usually refactor - but I never bother to refactor just for the sake of refactoring.I do appreciate the thought of a wast repository of cleanly coded plugins - but it just isn't realistic.
What is realistic is advocating good style for new plugins. And help out new scripters with best practices. There are loads of information on this forum - but unfortunately it's not properly organised.
What I like about SketchUp is that it has a low entry level - for its modelling and for it's scripting system. There are quite a number of people here that learned scripting for the first time writing SketchUp plugins. And this is where good examples are helpful - as one can learn quite a lot by reading other's code. But even if there was a perfect repository of plugins, the first script anyone writes won't be pretty. It's something one can not get away from.
-
@jessejames said:
What do you think SketchUp scripting is ThomThom -- a one for all wild west show? No Ruby scripting is NOT a collaboration project, it is an ENORMOUS collaboration project! We are a team of SketchUp developers. From the free open source to the freeware to the payware we ARE a giant team. And any team needs a few things to be succesfull
Implicit collaboration - bit of a stretch. I'd say that most are working alone. Yea, we share tips and techniques here on the forum. But it's nowhere near any explicit collaboration where mutual parters has gotten together for a joint purpose.
As I mentioned before - it is a good idea, but it's not realistic. You have a lot of enthusiasm, which is good, but I think you need to be a bit more pragmatic about your goals. What you propose are monumental tasks, and I can't see that there is enough people around that have the sufficient time and dedication for such a project.
@jessejames said:
What say ye...?
Retrofitting all plugins is something I'm sure will not happen.
But providing a good resource centre for new plugins and scripters is something I do believe can help.With more manageable tasks its more likely to get people on board.
-
Talking more about bad styles...
There are lots of amateur programmers among us ( and i am happy for that!) and a few really talented professional guys hanging around. It is of up most importance that we set a proper example for the new and up and coming scripters by writing code not only in a good style, but in a mutually accepted style so we are all setting the same example. I guarantee if WE write in a bad style they will just follow along thinking of sunshine and rainbows on the slow decent to hell-in-handbasket. Heck i've even seem @Last code that looked like lipstick on a pig!! What kind of example does that set? Huh?
Look we need to declare all out holy war against bad coding styles. We need to go through all the scripts at Ruby Library Depot, SketchUp scripts, and anywhere else we can get our grubby paws to, and re-write these abominations before too much damage is done
FURTHERMORE! We need to be yelling and screaming daily to Google, @Last, and anybody who will listen that WE NEED AN OFFICIAL SCRIPTS REPOSITORY! One that demands a script must meet certain style, documentation, and bug-free-ness to be included. We can still have all the other sites out there. But this site must be an official site that SketchUp users can find easily and trust that the code they download will be professional quality! This responsibility belongs to everyone who ever writes a script and releases it to the public!
There must be some kind of logical system we can employ to reign in this madness of multiplicity, mediocrity, and utterly destructive style complicity!
-
@thomthom said:
For collaboration projects it is good to have a set style - but very few such projects exists.
Oh i missed this juicy tidbit earlier...
What do you think SketchUp scripting is ThomThom? -- a one for all wild west show? Ruby scripting is NOT a mere "collaboration project", No, it is an ENORMOUS COLLABORATION PROJECT"! We are a team of SketchUp developers. From the free open source to the freeware to the payware. We are a giant team. And any team needs a few things to be succesfull
- A strong leader (Goolge/@Last)
- A battle plan (Style guide/Official Script Repository)
Without these two things Sparta will fall. All Greece will fall. Trust not in fools... honor the style gods. Honor the style guide!
"""We will stop our rotting code base by building the great SketchUp Code Repository! And from there, we will funnel this code into the filter we call a "style guide". Now, in that focused corridor of thought, it's numbers of current atrocious styles will count for nothing! And wave after wave of style abominations will smash against our logic shields. Bad Styles losses will be so great, it's atrocious influence so demoralized, it will have no choice but to abandon this destructive development cycle and yield to the very will of the SketchUp community!"""
What say ye...?
-
You don't learn a foreign language by reading a dictionary.
A dictionary should only tell you how people were using a language when it was written - not how you should use the language: after all a language doesn't belong to anyone, it can be used as its users see fit...
You learn [and evolve] a language by using it.
Any language has many dialects and ways of saying things.
Who says you are to be the 'language-police'?
There may be 'the best way' of saying something in English... but there are a dozen other ways of saying it that are almost as effective.
Some guides are good - things to avoid etc [local v. global variables, wrapping in a class or module etc], the fastest algorithms etc... but who's to say what you shouldn't do if it works for you ?
There's always room for improvement but you can't start speaking English like the Queen - that takes practice - and would make you sound pretty weird anyway!!!
Scripters [like the speakers of any 'real' language] will use the syntax and dialect that they are comfortable with.
I say it's better to let them at least try it whatever way they can that works, rather than stall because they don't understand or feel comfortable with some 'official' way of doing stuff...
My scripting can be a right mess but it usually works, and is easy enough to follow as I prefer 'English' syntax [if xxx==1; x=1; else; x=0; end; etc] - some others, who stray into Java like testing etc [xxx ? x==1 : x=0], I do find very difficult to follow - but it's just like a strong dialect in my own language .......
-
@jessejames said:
However! There really needs to be some templates for licensing posted at an official SketchUp site. Because most people (as you have showed yourself) do not complelely understand the legality of all these licenses and when to apply them.
I do believe there is a lengthy thread somewhere on this topic. ...don't have the link at hand though...
@jessejames said:
In all due respect i highly disagree with that statement and the attitude of laziness you display.
It ain't lazyness - it's prioritising. I spend all too much time on writing plugins, I doubt I'll be able to keep up the current pace for ever. With an array of ideas for new plugins I'd rather focus on creating new ones instead of reiterating old ones.
@jessejames said:
I seriously hope that i can make you realize how important proper style is and change your bad habits ThomThom. Because it's always much harder to unlearn a bad habit than to learn a new "good habit"!
I do realise good style is important, always have. But style is something one has to learn. Each time I write a plugin I improve. But the core if my point here is that I don't have the time to redo my previous ones.
@jessejames said:
And with you being a moderator statements like that have greater potential to destroy the will of the new scripter's to do the right thing and follow a prescribed style of code writing.
I don't discourage people from writing code in good style. By all means, if people want to go back to improve their coding, that is good. But from talking with the other scripters around here, there general sentiment we all tend to have is that there is too many ideas and too little time. And my personal belief is that you will be hard pressed to find people who prioritise rewriting over creating.
I wish you good luck with your endeavour.
-
There ya go: http://forums.sketchucation.com/viewtopic.php?f=180&t=16164
Some one and a half year ago.
-
@tig said:
You don't learn a foreign language by reading a dictionary.
Of course not! Your missing the point.
You could not learn any language from a dictionary alone! A dictionary only gives meaning to words. However to communicate in any language you not only need to know what each word "means" but how to construct many "meaningful" words into coherent structures called sentences and paragraphs that have a grander meaning then the sum of all their individual parts. Even if you knew every word in the English dictionary (most well educated don't) you still could not communicate to anyone coherently (even a 5 year old) with out understanding basic grammar and some sort of universally accepted style guide for writing sentences and paragraphs.
There are many fundamental values good written communication must have to work properly...
Symbols
Starting from the bottom you need symbols or letters that map to grunts and groans. Symbols are the basic building block.Words
Words that map to a mutually understood value or object. If my association of the word dog is that of a furry animal that barks and yours is to a tall plant with leaves then we are going to have a very hard time communicating. A dictionary is full of words that map to many other words which in turn provide meaning to the word in question -- but not much else can be learned from a dictionary alone! However lucky for us Ruby has defined the symbols and the words (largely taken from the English language) so we need not quarrel over these low level object. Symbols and words are provided by the gods so we need not question them. Therefore Symbols and words have nothing to do with style.Grammar
Grammar is the rules that define how to combine simple words to construct meaningful sentence objects (or statements) and further how you construct sentence objects into paragraph objects (or blocks) and furthermore up the chain of building blocks of how to construct entire modules, classes, and programs. In Ruby we can effect the grammar by how we write code --I'm not talking about indention here that is in layout-- i talking about choosing bad statement constructs that Ruby allows use to use -- which we should not! These are forbidden fruits!Layout
The "layout" (or visual aesthetics) of written language is concerned with how you organize the larger parts of the communication. You would not declare globals at the end of a script no more than you would start a lecture with the last paragraph. Just nonsense! There are rules and good reasons for having rules. This is where Indention comes into the argument. But indention is only part of the style issue!These are the required rules and objects that make up meaningful communication at the basic level. The "fundamental four" you might say. All these "rules" are necessary if you want to trans mutate your ideas (or objects) into the brain of your reader (or listener) in an effective way. Without them, you might as well just talk to a sea shell or write with disappearing ink because you're wasting your time.
When two entities communicate there must be rules that both the "sender" and the "receiver" understand mutually or the entire communication process will shut down and all attempts to communicate will be inevitably lost in translation.
Remember, language (whether verbal or written) is nothing more than me trying to take the electrical energy that is currently "excited" in my brain and recreate those same signals and "excitement" in your brain. If you think about it, using fancy grunts and groans or some chicken scratch on a piece of thin dried out tree bark is a very inefficient and error prone process for transferring a very physical process between two entities. It's subject to all sorts of interference, mis-communications, mis-understandings, and mis-interpretations than one can shake a stick at. The LAST thing we want to do is induce more entropy into this moronic system of communication!
-
@unknownuser said:
My reason is that I have never bothered to look do closely at this whole open source concept. I know I use lots of software that are open source, but there are so many licenses out there to choose from - each with a long chuck of text with many clauses that it's hard to get an overview. And I also have no idea of what each license does - some let people use it commercial purposes etc. So I find it easier to just let people ask me and state their purpose.
I agree the amount of licenses available and understanding the clauses are a task better suited for tax code lawyers. However really all you need to concentrate on is a few small words...
- use
- copy
- modify
- distribute
- commercial
Thats really all you need for open sourcing a script...
# Copyright YEARHERE, NAMEHERE. # # Permission to use, copy, modify, and distribute this software for # any purpose and without fee is hereby granted, provided that the above # copyright notice appear in all copies. # # THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
However! There really needs to be some templates for licensing posted at an official SketchUp site. Because most people (as you have admitted yourself) do not complelely understand the legality of all these licenses and when to apply them.
Choosing the wrong license spec can be damaging to the entire community. We desperately need some templates so everybody can copy paste the same license (of which they can choose from three) in the following categories...
- Completely open source license.
- Completely free to use for personal use only!
- Free to use only!...and hopefully we will place these in the same place as the official script repository!
Of course Google and @Last should be pushing for ALL scripts to be completely open source or at least open source for personal usage. Of course --as i stated before-- i am not against people close sourcing "certain" scripts if they have done a substantial amount of groundbreaking work on them. But Google's official statement should promote the fee exchange of ideas, technology, and collaboration. That's IMO! Push the completely open source and frown on the closed.
@thomthom said:
@jessejames said:
Look we need to declare all out holy war against bad coding styles. We need to go through all the scripts at Ruby Library Depot, SketchUp scripts, and anywhere else we can get our grubby paws to, and re-write these abominations before too much damage is done
This just ain't going to happen.
In all due respect i highly disagree with that statement and the attitude of laziness you display. ThomThom, you have always been and continue to be one of my favorite people around here but please don't make damning statements like that. That very attitude is why we have found ourselves in such a pitiful state today. And with you being a moderator statements like that have greater potential to destroy the will of the new scripter's to do the right thing and follow a prescribed style of code writing.
@thomthom said:
All these scripts are written by people on their own time. Most are written by non-professional like me. And many are written for a small specific purpose just to get the job done. I doubt there are many enthusiastic about re-working everything just for the sake of making the code pretty while not providing any advantage for end user. I certainly have no interest, and most importantly time, for such a huge task.
Thats great that people give their time to do this however they need to realize the damage that is done from use a bad style. Bad styles are like a hereditary disease, they get passed down from generation to generation. Some one has to put a stop to that infestation at some point. And i hope we can all agree to apply the cure before it's too late!
@thomthom said:
Whenever I pick up an old plugin of mine to add some new features I do usually refactor - but I never bother to refactor just for the sake of refactoring.
I seriously hope that i can make you realize how important proper style is and change your bad habits ThomThom. Because it's always much harder to unlearn a bad habit than to learn a new "good habit"! Hopefully we caught the problem before it becomes terminal.
@thomthom said:
I do appreciate the thought of a wast repository of cleanly coded plugins - but it just isn't realistic.
But it is realistic ThomThom, we can go back and change the scripts if we can get the larger community speaking with the same voice. I would love to contribute myself at re-working these scripts -- and i will. However for the "non modifiable" licenses we will need the authors permission. Thats why we need peer pressure to make this work. It WILL work if you believe that it will. And we should use that peer pressure to encourage full open sourcing where applicable!
@thomthom said:
What is realistic is advocating good style for new plugins. And help out new scripters with best practices. There are loads of information on this forum - but unfortunately it's not properly organised.
I highly agree. At the very least we cannot. And we should not allow future scripts to be so sloppy. If we do the endless cycle repeats...
while lazy code_sloppy() end
@thomthom said:
What I like about SketchUp is that it has a low entry level - for its modelling and for it's scripting system.
Absolutely! And offering these budding chaps clean code will only serve to quicken the pace of their learning. There is no downside to accepting a good style of coding. Everyone will benefit in the end
-
@jessejames said:
FURTHERMORE! We need to be yelling and screaming daily to Google, @Last, and anybody who will listen ...
FYI: @Last Software no longer exists.
Google acquires @Last Software
Yelling and screaming and insulting hasn't worked. We've tried it (and given up.)
The same old bugs are still in the application we've cried about for years. (Shadow bug.)
Everyday we discover another missing method that should have always been in the API, or another Registry setting we cannot access or a property of a Drawingelement subclass that has no attribute accessors. ..etc.. etc. (I have become weary of doing hours and hours of work proofreading the API docs and identifying bugs and shortcomings of the API itself without getting paid. If the Sketchup API was OpenSource, I would feel differently, but it's not. Google is one of the largest software companies in the world and can afford to hire the gurus to get done what needs to be done, if they wished to. It has become obvious to me that corporate Google either does not know the bad state of the API and it's documentation; or they do not care. I think they see Sketchup as a mere utility that supports the "real" product Google Earth.)I'm thinking the world needs a TRUE OpenSource 3D Modeling Application Project that supports multiple scripting engines (Ruby, Python and OpenBasic,) to name a few.
But I'm going off topic here...
-
@dan rathbun said:
I'm thinking the world needs a TRUE OpenSource 3D Modeling Application Project that supports multiple scripting engines (Ruby, Python and OpenBasic,) to name a few.
Blender? Might not support multiple languages - but it's fully open source.
-
@thomthom said:
Blender? Might not support multiple languages - but it's fully open source.
I was thinking of making scripting APIs for BRL-CAD
http://brlcad.org/It was written at Berkley Research Labs with public funds (I believe. I'm under the impression that NASA uses it for some of it's graphics.) I had downloaded the code back about 10 years but never did anything with it. It has been updated many times since then.
-
@jessejames said:
Modules and Classes ...to indent or not to indent. That is the question!
I have said it before and i'll say it again... the module syntax is clutter and it would be more elegant to use the file as the module (like Python does) however thats a Ruby issue and we need to accept that for now.Your dang right you have to accept it.. because never have you been more wrong James!
THIS issue is by a large margin more important than proper indenting. (Poorly indented or ugly style scripts don't "crap" on my code. Any non-coding user and I, will never know how ugly they may be unless we open the code in an editor. If the code works, however ugly, what does it matter if it's never seen.) I'm all for good indenting, and I HATE outdenting!
Module syntax is NOT clutter. If you (speaking generally to all readers and especially newbies,) do not understand the importance of modules, then you do not understand how Ruby operates and how code is (and should be,) loaded.
Modules separate your code from other people's code, and prevent your code from "crapping" on the ObjectSpace (which is the same as "crapping" on everyone else's modules and classes, including Google's and Ruby's.) ANY script that defines methods, instance variables, class variables or constants in the ObjectSpace IS "crap." It does not matter if Google did it in their examples, it is still "crap."
Not only should you be using A module around your script... you should be using nested modules. The outermost is your TOP_LEVEL namespace, Ex(using your SCF screenname):
module JesseJames
Any tool or plugin you create should be in a nested module (submodule,) of your TOP_LEVEL namespace. This allows individual tools or plugins to be removed from memory when they are no longer being used. TOP_LEVEL modules and classes can NOT be removed (by design.) This means the standard Ruby modules and classes, and Google's Sketchup, UI and Geom modules are safe. It also means a malicous coder cannot remove YOUR top level namespace. (It also means Google incorrectly put their modules at the toplevel, when they should have been within module Google. What happens in the future when Layout gets an API, and/or Picasa gets a Ruby API that integrates to Sketchup and Layout?)Back to indenting... anticpating a chorus of whiney voices, thus:
"Oh man, nested modules mean I have to waste so much space on the left of my code, and push the "meat" of my rubies way to the right! And then I have to hit that TAB key all the time on every line... boohoo!"
No you don't! Ruby allows multiple scope defintions !
If I wish to define a class within a submodule of my toplevel module, I can do so and only have 1 indent:unless defined?(;;MyTopLevel)=='module' module ;;MyTopLevel end end # unless unless defined?(;;MyTopLevel;;MyPlugin)=='module' module ;;MyTopLevel;;MyPlugin end end # unless # The Outer namespace modules must exist before referencing them class ;;MyTopLevel;;MyPlugin;;ThisClass def initialize(*args) # INIT CODE GOES HERE end # def end # class ;;MyTopLevel;;MyPlugin;;ThisClass
[You don't need the definition test(s) if you KNOW that the outer module(s) have already been created (like their definitions had preceeded this class definition in the same file, OR this file "requires" the file that defined the outer modules.)]
I can also save an indent when defining a plugin module by doing:
unless defined?(;;MyTopLevel)=='module' module ;;MyTopLevel end end # unless # The Outer namespace module must exist before referencing it module ;;MyTopLevel;;MyPluginTwo class<<self private def method_one # .. code .. end public def method_two # .. code .. end # .. etc .. end # self end # module ;;MyTopLevel;;MyPluginTwo
instead of doing this:
module MyTopLevel module MyPluginTwo class<<self private def method_one # .. code .. end public def method_two # .. code .. end # .. etc .. end # self end # module MyPluginTwo end # module MyTopLevel
Let's save Ruby vs Python for another topic thread, but for now, let me say in regard to your statement:
@jessejames said:...it would be more elegant to use the file as the module (like Python does)..
that this CAN be done in Ruby using the wrap parameter of the load method. However it is simplistic and lacks control. The script is loaded into a temporary Anonymous namespace (module,) that is removed from memory when the script ends. So the important lesson here is the lack of controlling the namespace(s) under which the code runs, as well as controlling the persistance of the objects the code may create.
Your just better off wrapping the code the namespace(s) ie, modules of your choice, to begin with.I have been tempted to write a Toilet plugin, that will load "crappy" scripts into namespace:
::Toilet::Crap
and when done, "flush the toilet" so to speak by calling ::Toilet.flush which would remove the submodule Crap. I am musing over the idea to have a scanner that would scan scripts to determine if they do "crappy" things, like defining $global variables for one time use, and converting them to module vars.
But number 1 on the list of "crappy" things, (drumroll,) is defining custom classes at the top level (ie, within Object.) ONLY Ruby base classes generic to the entire Ruby universe should be declared at the top level. (And yes Google broke that rule in a few places, but it does not negate the rule. Example: The custom Sketchup Set class is defined at the top level, instead of as Sketchup::Set, and will clash with Ruby's standard Set class, if you load the latter.) -
@dan rathbun said:
Module syntax is NOT clutter. If you (speaking generally to all readers and especially newbies,) do not understand the importance of modules, then you do not understand how Ruby operates and how code is (and should be,) loaded.
Modules separate your code from other people's code, and prevent your code from "crapping" on the ObjectSpace (which is the same as "crapping" on everyone else's modules and classes, including Google's and Ruby's.) ANY script that defines methods, instance variables, class variables or constants in the ObjectSpace IS "crap." It does not matter if Google did it in their examples, it is still "crap."
NO CRAP Dan! Don't lecture me about the fundamentals of modules and namespaces. I know first hand the importance of modules. For without them, we would have so many name clashes that nobody could write code that did not blow chunks! The API would fall apart.
What i am referring to is the fact that Ruby makes you explicitly define module namespace! Wrapping up namespaces between syntax is a complete waste of time WHEN Ruby should create the module from each separate file -- like Python does! Python handles this so much more beautifully.
In Python, a programmer creates a module simply by writing code in a file. THE FILE WILL THEN BECOME THE MODULE. Do you see the beauty of such a system Dan? Even if you write toplevel code in the file (psst: thats a module Dan!) it does not matter. The code will be insulated from the global namespace by the module's namespace (psst: thats the file Dan!). And guess what else Dan...the FILE NAME then becomes the MODULE NAME. Woohoo! No need for more redundant syntax like Ruby forces on the programmer!
Ruby's modules are a monkey patch because Matz did not think far enough ahead when designing Ruby. Then he had to pull a "rabbit-out-of-his-hat" and came up with this module...code...end monkey business.
In Python, when we want to bring in all the names of a module we use the **from module import *** -- That means import everything. It's very much the same as what Ruby does with require HOWEVER, python gives you even more leverage with the from module import name1, name2, ..., nameN. With this statement you can choose to only bring in a few names and not the whole polluting shebang! But thats not all Dan, oh no, you can even import names and give them alias's right on the spot with the syntax from module import X as _X, y as WhyAskWhy, .... You see Dan Python is a far better choice for any scripting environment. Python was built with this very thing in mind from day one.
@dan rathbun said:
Not only should you be using A module around your script... you should be using nested modules. The outermost is your TOP_LEVEL namespace, Ex(using your SCF screenname):
module JesseJames
Any tool or plugin you create should be in a nested module (submodule,) of your TOP_LEVEL namespace. This allows individual tools or plugins to be removed from memory when they are no longer being used. TOP_LEVEL modules and classes can NOT be removed (by design.) This means the standard Ruby modules and classes, and Google's Sketchup, UI and Geom modules are safe. It also means a malicous coder cannot remove YOUR top level namespace. (It also means Google incorrectly put their modules at the toplevel, when they should have been within module Google. What happens in the future when Layout gets an API, and/or Picasa gets a Ruby API that integrates to Sketchup and Layout?)Sadly all this nonsense would be unnecessary if we would adopt Python. Then we could concentrate on actually writing the meat and potatoes of our software instead of constantly worrying about name clashes from a scripting language with a piss poor design philosophy! Ruby is good for personal use and not much else.
@dan rathbun said:
Back to indenting... anticpating a chorus of whiney voices, thus:
Thanks for showing the class about how to maintain proper indention whist keeping the left margin minimal. This was a great and informative piece of text that should be posted some where were all can see and learn from.
@dan rathbun said:
Let's save Ruby vs Python for another topic thread, but for now, let me say in regard to your statement:
@jessejames said:...it would be more elegant to use the file as the module (like Python does)..
that this CAN be done in Ruby using the wrap parameter of the load method. However it is simplistic and lacks control. The script is loaded into a temporary Anonymous namespace (module,) that is removed from memory when the script ends. So the important lesson here is the lack of controlling the namespace(s) under which the code runs, as well as controlling the persistance of the objects the code may create. Your just better off wrapping the code the namespace(s) ie, modules of your choice, to begin with.Well i agree there is not much we can do. Our hands are tied. And not only with extending and patching this API, but also with the Ruby language proper as it too is boxing us in. We are basically surrounded on all sides by asininity and there seems to be no way out of this mess. Well, there is a way but trying to convince Ruby religious fanatics around here that greener pastures exists is almost a fruitless endeavor.
@dan rathbun said:
I have been tempted to write a Toilet plugin...<snip>...(And yes Google broke that rule in a few places, but it does not negate the rule. Example: The custom Sketchup Set class is defined at the top level, instead of as Sketchup::Set, and will clash with Ruby's standard Set class, if you load the latter.)
Ah yes. When the gods lead by bad example then the lemmings will follow them strait off the cliff. We need to do something about this mess Dan. You seem to be a smart, professional minded programmer. We need to get together, have a few beers, and discuss a battle plan for retaking this lost ship.
Currently SketchUp scripting is a captain-less ship left to the sport of every hacks whim. Someone needs to step in and lead by example. Rule with an iron fist, and kick some major butt around here. In times like these it takes drastic measures to bring about drastic changes. But in the end we will set sail on calmer seas. And graze on greener pastures.
-
@thomthom said:
@dan rathbun said:
I'm thinking the world needs a TRUE OpenSource 3D Modeling Application Project that supports multiple scripting engines (Ruby, Python and OpenBasic,) to name a few.
Blender? Might not support multiple languages - but it's fully open source.
Blender is a great open source environment for organic modeling, rendering, animation, and more. However for architectural stuff it sucks. And the people who are in charge of Blender have no plans to change that -- believe me i know! Blender is good complement to SketchUp but it will never be anything even close to a replacement for SketchUp.
PS: Blender has the most bone headed UI every created! This is one of the reasons it will only be a niche toy for a very small group of Blender heads.
Advertisement