I've been following GUI extensions and notice examples use either _isEnabled or isEnabled, without the underscore. Both seem to work to extend or possibly replace existing functionality.
isEnabled
For example, the PowerTools base class (which doesn't seem to "extend" existing functionality) has:
PowerTools.BaseCommand.prototype.isEnabled = function(selection, pipeline)
{
var p = this.properties;
if (!p.initialized)
{
this.initialize();
}
if (!this.isToolConfigured())
{
return false;
}
if (this.isValidSelection)
{
return this.isValidSelection(selection, pipeline);
}
return true;
};
A tool can use this base class and declare .isValidSelection, for example:
PowerTools.Commands.CountItems.prototype.isValidSelection =
function (selection) { ... }
_isEnabled
I see Anguilla uses ._isEnabled for existing functionality (in Chrome's console in numerous places in the code). For example, WhereUsed has:
Tridion.Cme.Commands.WhereUsed.prototype._isAvailable =
function WhereUsed$_isAvailable(selection) ...
Private functions?
I'm familiar with a preceding underscore being a naming convention for private variables. Are the _isEnabled and other functions that start with an underscore "private?" If so, then
How should we extend (add additional functionality to existing code) these functions?
How should we replace (not have existing code run, but have ours run instead as in an "override") these?
I'm assuming the same approach applies to other functions that start with an underscore such as _isAvailable, and _invoke.
The following methods are called for a command:
isAvailable
isEnabled
invoke
The base class for all commands - Tridion.Core.Command - has a standard implementation of these methods. For the most part, this default implementation allows for extensions to Commands. They also call the underscore methods (_isAvailable, _isEnabled, and _execute).
I don't know why the CME commands only overwrite the underscore methods. Maybe someone thought it was just easier that way. They should be consider private (or the equivalent of "protected" in C#), so it actually seems like a bad practice to me.
It would be cleaner to implement the proper methods (isAvailable, isEnabled, and invoke) and then call the base implementation using this.callBase. However, you might need to stop the pipeline in this case, or also overwrite the underscore methods, in order to avoid your return value getting overwritten by the default underscore methods. It depends on the command you are implementing or extending.
In short: using the underscore methods is probably bad practice, but the Core implementation does seem to make it harder for you to do it "right". So I'd aim to avoid the underscore methods, but not sweat it if it turns out to be too hard to do so.
P.S. isValidSelection is a PowerTools-only method which separates the common logic that they all need from the logic specific to each command.
Related
I am writing unit tests for some async sections of my code (returning Futures) that also involves the need to mock a Scala object.
Following these docs, I can successfully mock the object's functions. My question stems from the fact that withObjectMocked[FooObject.type] returns Unit, where async tests in scalatest require either an Assertion or Future[Assertion] to be returned. To get around this, I'm creating vars in my tests that I reassign within the function sent to withObjectMocked[FooObject.type], which ends up looking something like this:
class SomeTest extends AsyncWordSpec with Matchers with AsyncMockitoSugar with ResetMocksAfterEachAsyncTest {
"wish i didn't need a temp var" in {
var ret: Future[Assertion] = Future.failed(new Exception("this should be something")) // <-- note the need to create the temp var
withObjectMocked[SomeObject.type] {
when(SomeObject.someFunction(any)) thenReturn Left(Error("not found"))
val mockDependency = mock[SomeDependency]
val testClass = ClassBeingTested(mockDependency)
ret = testClass.giveMeAFuture("test_id") map { r =>
r should equal(Error("not found"))
} // <-- set the real Future[Assertion] value here
}
ret // <-- finally, explicitly return the Future
}
}
My question then is, is there a better/cleaner/more idiomatic way to write async tests that mock objects without the need to jump through this bit of a hoop? For some reason, I figured using AsyncMockitoSugar instead of MockitoSugar would have solved that for me, but withObjectMocked still returns Unit. Is this maybe a bug and/or a candidate for a feature request (the async version of withObjectMocked returning the value of the function block rather than Unit)? Or am I missing how to accomplish this sort of task?
You should refrain from using mockObject in a multi-thread environment as it doesn't play well with it.
This is because the object code is stored as a singleton instance, so it's effectively global.
When you use mockObject you're efectibly forcefully overriding this var (the code takes care of restoring the original, hence the syntax of usign it as a "resource" if you want).
Because this var is global/shared, if you have multi-threaded tests you'll endup with random behaviour, this is the main reason why no async API is provided.
In any case, this is a last resort tool, every time you find yourself using it you should stop and ask yourself if there isn't anything wrong with your code first, there are quite a few patterns to help you out here (like injecting the dependency), so you should rarely have to do this.
How can I tell the Closure Compiler not to rename an inner function? E.g., given this code:
function aMeaninglessName() {
function someMeaningfulName() {
}
return someMeaningfulName;
}
...I'm fine with Closure renaming the outer function (I actively want it to, to save space), but I want the function name someMeaningfulName left alone (so that the name shown in call stacks for it is "someMeaningfulName", not "a" or whatever). This despite the fact that the code calling it will be doing so via the reference returned by the factory function, not by the name in the code. E.g., this is purely for debugging support.
Note that I want the function to have that actual name, not be anonymous and assigned to some property using that name, so for instance this is not a duplicate of this other question.
This somewhat obscure use case doesn't seem to be covered by either the externs or exports functionality. (I was kind of hoping there'd be some annotation I could throw at it.) But I'm no Closure Compiler guru, I'm hoping some of you are. Naturally, if there's just no way to do that, that's an acceptable answer.
(The use case is a library that creates functions in response to calls into it. I want to provide a version of the library that's been pre-compressed by Closure with SIMPLE_OPTIMIZATIONS, but if someone is using that copy of the library with their own uncompressed code and single-stepping into the function in a debugger [or other similar operations], I want them to see the meaningful name. I could get around it with eval, or manually edit the compressed result [in fact, the context is sufficiently unique I could throw a sed script at it], but that's awkward and frankly takes us into "not worth bothering" territory, hence looking for a simple, low-maintenance way.)
There is no simple way to do this. You would have to create a custom subclass of the CodingConvention class to indicate that your methods are "local" externs (support for this was added to handle the Prototype library). It is possible that InlineVariables, InlineFunctions, or RemoveUsedVariables will still try to remove the name and would also need to be fixed up.
Another approach is to use the source maps to remap the stack traces to the original source.
read the following section
https://developers.google.com/closure/compiler/docs/api-tutorial3#export
Two options basically, use object['functionName'] = obj.functionName or the better way
use exportSymbol and exportProperty both on the goog object, here is the docs link for that
http://closure-library.googlecode.com/svn/docs/closure_goog_base.js.html
-- edit
ah, i see now, my first answer is not so great for you. The compiler has some interesting flags, the one which might interest you is DEBUG, which you can pass variables into the compiler which will allow you to drop some debugging annotations in via logging or just a string which does nothing since you are using simple mode.
so if you are using closure you can debug against a development version which is just a page built with dependiencies resolved. we also the drop the following in our code
if(DEBUG){
logger.info('pack.age.info.prototype.func');
}
I want to handle multiple operations on a UI Component (button ,textfield, swfs,custom objects etc)
in like scaling,skewing ,color,rotations etc etc and save them too. Earlier the actions were done
using a single tool and single mxml file but now the tool is separated into different tools.
Was wondering how i can design / use something like Toolmanager class to handle actions etc?
Also the tricky part is that some objects can have more operations defined for them .
Like 'object1' has 3 operations that can be performed on it and 'object2' has 5 operations defined on it.
We are using MVC design pattern but no frameworks as such.
What are the different design patterns that can be used to do this?
Edit:
To be more precise i want implement this in AS3 OO way.
The application is similar to drawing application which supports addition of various images,text,audio,swfs etc. One added user can perform various operations of the objects..like
adding color,scaling skewing,rotation etc etc and custom effects and after that export the drawing as PNG.Likewise some effects that are applicable to text are not applicable to images
and vice versa. and some effects can be common.
Any ideas?
Probably you could have a toolbar, tools(inheriting from a common base), and some kind of property panel, these objects are accessible from a manager class which wrappes them together and makes some variables accessible for all classes.
Probably you want a selection array or vector in the manager class and a select tool to manipulate this collection
like (in the manager)
protected var _selection:Vector.<EditableBase> = new Vector.<EditableBase>();
public function get selection() { return _selection;}
and a collection about the editbase extensions and the tools avaiable for them.
every time the selection tool updates the selection collection (probably calling a method on manager from the select tool's onMouseUp method) you can update the toolbar to display the apropriate tools for the current selection
(in manager)
protected var _ToolsByType:Object (or Dictionary) = {"EditableAudio": ["toolA", "toolB", etc]};
protected var _defaultSet:Array = ["toolA", "toolB"];
and after the selection has benn manipulated (in manager also)
public function onSelectionChangedCallback():void
{
var toolsToDisplay:Array = _defaultSet;
if(_selection.length == 1)
{
//not actual syntax
var type:String = getQualifiedClassName(_selection[0]);
if(type in _ToolsByType) toolsToDisplay = _ToolsByType[type];
}
myToolBar.showSet(toolsToDisplay);
}
the ancestor for the tools should look something like this:
public class ToolBase
{
protected var _manager:ToolManager;
function ToolBase(manager:ToolManager)//and probably a bunch of other params as well
{
_manager = manager;
}
function onSelect()
{
//you can manipulate the properties panel here
}
function onDeSelect()...
function onMouseDown(mouseData:event/whateverWrapperYouHaveCreated)...
function onMouseMove...
function onMouseUp...
}
and so and so on :)
kinda straight forward.
check photoshop plugin tutorials, or google around "extending {any adobe stuff here, like flash or something}
thats javascript but the concept can be applied here as well
maybe you could use the Strategy Design Pattern by creating some extra classes in your MVC implementation
http://en.wikipedia.org/wiki/Strategy_pattern
algo, check this tool for images:
http://www.senocular.com/demo/TransformToolAS3/TransformTool.html
bye! :)
I have a flex application, and I am using a cairngorm structure -
src/com/mysite/editor/model/ contains the following two things
EditorModelLocator.as (Singleton Enforced Application Globals),
EditorGlobalConstants.as (Contains All constants), like the following
public static const SUPPORT_PHONE:String = '800-865-7496';
public static const SUPPORT_EMAIL:String = 'support#mysite.com';
I was wondering where the best place to put helper methods is. I need these to be methods I can use outside of the singleton enforced class. Would it make sense to put it in Global Constants? The only thing against that, is I always use EditorGlobalConstants the same way:
EditorGlobalConstants.SUPPORT_PHONE
An example of a 'helper function' is the following:
public var blank(value:String):Boolean {
if( value == '' || value == null ) return true;
return false;
}
I can store all of this information in EditorGlobalConstants, but I was wondering if maybe EditorHelpers.as would be better, and how I would instantiate/use that solution?
Thanks!
Andrew Thorp
Not familiar with how cairngorm tends to do things, but in AS3 functions don't have to be part of a class.
For instance, you could have a file called helperFunction.as with the contents:
package my.package {
public function helperFunction(arg1:Object, arg2:String):void {
// Do stuff
}
}
Then just import that method like you would anything else:
import my.package.helperFunction
and you can use it in your code.
Just pick a package that would make sense for the method to live in (probably in the same package that the objects it's meant to help with are defined).
If you're going to use your helper methods not only in your singleton class, it would be better to place them somewhere upper in hierarchy. You can easily find that place by yourself. Let's try:
Break up your application (in imagination/paper/whatever) into a boxes. Each class is a separate box.
Put them into structure. You just need to see, which boxes are placed inside which ones.
Mark the boxes-classes, where are you going to use these methods.
Find the top level, where are you going to use them and place your class there.
Let's see an example .. suppose you have this structure:
ToplevelApplication
|-BoxAtLevel_1
| |-BoxAtLevel_2
...
if I want my helpers used only in BoxAtLevel_2, I'd put them there:
|-BoxAtLevel_1
| |-BoxAtLevel_2
| |-Helpers
And so on .. if you have any troubles - put your structure here, and I'll help.
Also, about EditorHelpers.as .. is this an instance-level things or rather class-level ones? That's what going to set the way you'll use them.
I'm in my module file. I want to define some complex variables for use throughout the module. For simple things, I'm doing this:
function mymodule_init() {
define('SOME_CONSTANT', 'foo bar');
}
But that won't work for more complex structures. Here are some ideas that I've thought of:
global:
function mymodule_init() {
$GLOBALS['mymodule_var'] = array('foo' => 'bar');
}
variable_set:
function mymodule_init() {
variable_set('mymodule_var', array('foo' => 'bar'));
}
property of a module class:
class MyModule {
static $var = array('foo' => 'bar');
}
Variable_set/_get seems like the most "drupal" way, but I'm drawn toward the class setup. Are there any drawbacks to that? Any other approaches out there?
I haven't seen any one storing static values that are array objects.
For simple values the drupal way is to put a define in the begining of a modules .module file. This file is loaded when the module is activated so that is enough. No point in putting it in the hook_init function.
variable_set stores the value in the database so don't run it over and over. Instead you could put it in your hook_install to define them once. variable_set is good to use if the value can be changed in an admin section but it's not the best choice to store a static variable since you will need a query to fetch it.
I think all of those methods would work. I have never used it in this fashion, but I believe the context module (http://drupal.org/project/context) also has its own API for storing variables in a static cache. You may want to check out the documentation for the module.
It's always a good practice to avoid globals. So that makes your choice a bit easier.
If you err towards a class, you'll be writing code that is not consistent with the D6 standards. There are a lot of modules that do it but I personally like to keep close to the Drupal core so I can understand it better. And code that's written in different styles through the same application can have an adverse effect on productivity and maintenance.
variable_set() and define() are quite different. Use the former when you can expect that information to change (a variable). Use the latter for constants. Your requirements should be clear as which one to use.
Don't worry too much about hitting the database for variable_set/get. If your software is written well, it should not effect performance hardly at all. Performance work arounds like that should only be implemented if your applications has serious performance issues and you've tried everything else.